简体   繁体   English

在ASP.NET C中抛出异常#

[英]Throwing exceptions in ASP.NET C#

Is there a difference between just saying throw; 只是说throw;之间有区别吗throw; and throw ex; throw ex; assuming ex is the exception you're catching? 假设ex是你正在捕捉的例外吗?

throw ex; will erase your stacktrace. 将擦除你的堆栈跟踪。 Don't do this unless you mean to clear the stacktrace. 除非你想清除堆栈跟踪,否则不要这样做。 Just use throw; 只需使用throw;

Here is a simple code snippet that will help illustrate the difference. 这是一个简单的代码片段,有助于说明差异。 The difference being that throw ex will reset the stack trace as if the line " throw ex; " were the source of the exception. 不同之处在于throw ex将重置堆栈跟踪,就像“ throw ex; ”行是异常的来源一样。

Code: 码:

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();
        }
    }
}

Output (notice the different stack trace): 输出(注意不同的堆栈跟踪):

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

You have two options throw; 你有两个选择; or throw the orginal exceptional as an innerexception of a new exception. 或抛出原始例外作为新例外的一个例外。 Depending on what you need. 根据您的需要而定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM