在 ASP.NET C# 中抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/88490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Throwing exceptions in ASP.NET C#
提问by Chris Westbrook
Is there a difference between just saying throw;
and throw ex;
assuming ex
is the exception you're catching?
只是说throw;
和throw ex;
假设ex
是你捕捉到的例外有区别吗?
采纳答案by GEOCHET
throw ex;
will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use throw;
throw ex;
将删除您的堆栈跟踪。除非您想清除堆栈跟踪,否则不要这样做。只需使用throw;
回答by GEOCHET
You have two options throw; or throw the orginal exceptional as an innerexception of a new exception. Depending on what you need.
你有两个选择投掷;或将原始异常作为新异常的内部异常抛出。取决于你需要什么。
回答by Eric Schoonover
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
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