web-dev-qa-db-ja.com

ASP.NET C#で例外をスローする

exがあなたが捕らえている例外であると仮定して、throw;throw ex;を言うだけの違いはありますか?

24
Chris Westbrook

throw ex;はスタックトレースを消去します。スタックトレースをクリアするつもりがない限り、これを行わないでください。 throw;を使用するだけです

43
GEOCHET

これは、違いを説明するのに役立つ簡単なコードスニペットです。違いは、throw exは、「_throw ex;_」行が例外のソースであるかのようにスタックトレースをリセットすることです。

コード:

_using System;

namespace StackOverflowMess
{
    class Program
    {
        static void TestMethod()
        {
            throw new NotImplementedException();
        }

        static void Main(string[] args)
        {
            try
            {
                //example showing the output of throw ex
                try
                {
                    TestMethod();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine();
            Console.WriteLine();

            try
            {
                //example showing the output of throw
                try
                {
                    TestMethod();
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}
_

出力(異なるスタックトレースに注意してください):

_System.NotImplementedException: The method or operation is not implemented._
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 23

_System.NotImplementedException: The method or operation is not implemented._
at StackOverflowMess.Program.TestMethod() in Program.cs:line 9
at StackOverflowMess.Program.Main(String[] args) in Program.cs:line 43

18
Eric Schoonover

2つのオプションがあります。または、元の例外を新しい例外の内部例外としてスローします。必要なものに応じて。

2
user1333