【问题标题】:Throwing exceptions in ASP.NET C#在 ASP.NET C# 中引发异常
【发布时间】:2010-09-10 10:48:27
【问题描述】:

假设ex 是您要捕获的异常,只说throw;throw ex; 有区别吗?

【问题讨论】:

    标签: c# .net exception


    【解决方案1】:

    throw ex; 将清除您的堆栈跟踪。除非您要清除堆栈跟踪,否则不要这样做。只需使用throw;

    【讨论】:

    • 我从未见过,尽管可能有。如下所述,我听说过将它附加到内部异常,但我想不出你会想要销毁堆栈跟踪的任何理由。
    【解决方案2】:

    这里有一个简单的代码 sn-p 可以帮助说明差异。不同之处在于 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

    【讨论】:

      【解决方案3】:

      你有两个选择扔;或将原始异常作为新异常的内部异常抛出。看你需要什么。

      【讨论】:

        猜你喜欢
        • 2014-01-10
        • 2017-03-26
        • 2010-09-21
        • 1970-01-01
        • 1970-01-01
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多