24

ただ言うことと、あなたがキャッチしている例外であるthrow;throw ex;仮定することの間に違いはありますか?ex

4

3 に答える 3

44

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

于 2008-09-17T22:55:37.443 に答える
18

違いを説明するのに役立つ簡単なコード スニペットを次に示します。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

于 2008-09-17T23:10:45.863 に答える
2

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

于 2008-09-17T23:03:26.833 に答える