有一些帖子问这两者之间已经有什么区别了。(为什么我要提这个…)
但我的问题在某种程度上是不同的,我在另一种错误处理方法中调用了“throw ex”。
public class Program {
public static void Main(string[] args) {
try {
// something
} catch (Exception ex) {
HandleException(ex);
}
}
private static void HandleException(Exception ex) {
if (ex is ThreadAbortException) {
// ignore then,
return;
}
if (ex is ArgumentOutOfRangeException) {
// Log then,
throw ex;
}
if (ex is InvalidOperationException) {
// Show message then,
throw ex;
}
// and so on.
}
}
如果在主线中使用try和catch,那么我会使用throw;重新抛出错误。
但是在上面的简单代码中,所有异常都通过HandleException
是否抛出前任;在HandleException内部调用时,与调用throw有相同的效果?
微软文档代表:
Once an exception is thrown, part of the information it carries is the stack trace. The stack trace is a list of the method call hierarchy that starts with the method that throws the exception and ends with the method that catches the exception. If an exception is re-thrown by specifying the exception in the throw statement, the stack trace is restarted at the current method and the list of method calls between the original method that threw the exception and the current method is lost. To keep the original stack trace information with the exception, use the throw statement without specifying the exception.
来源:https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2200
微软文档代表:
Once an exception is thrown, part of the information it carries is the stack trace. The stack trace is a list of the method call hierarchy that starts with the method that throws the exception and ends with the method that catches the exception. If an exception is re-thrown by specifying the exception in the throw statement, the stack trace is restarted at the current method and the list of method calls between the original method that threw the exception and the current method is lost. To keep the original stack trace information with the exception, use the throw statement without specifying the exception.
来源:https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2200
看这里:http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html
把:
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}
它保留了异常堆栈信息
这叫做"重扔"
如果想要抛出新的异常,
throw new ApplicationException("operation failed!");
把交货:
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}
它不会发送异常堆栈信息
这叫做“打破堆栈”
如果想要抛出新的异常,
throw new ApplicationException("operation failed!",ex);