有些帖子询问这两者之间的区别。
(为什么我要提这个...)
但我的问题在某种程度上有所不同,我在另一个错误神级处理方法中调用了“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.
}
}
如果在 Main
中使用了 try & catch
,那么我会使用 throw;
来重新抛出错误。
但是在上面的简化代码中,所有的异常都经过HandleException
在HandleException
中调用throw ex;
是否和调用throw
效果一样?
最佳答案
是的,有区别。
throw ex
重置堆栈跟踪(因此您的错误看起来源自HandleException
)throw
不会 - 原始违规者将被保留。static void Main(string[] args) { try { Method2(); } catch (Exception ex) { Console.Write(ex.StackTrace.ToString()); Console.ReadKey(); } } private static void Method2() { try { Method1(); } catch (Exception ex) { //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main) throw ex; } } private static void Method1() { try { throw new Exception("Inside Method1"); } catch (Exception) { throw; } }
关于c# - "throw"和 "throw ex"之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/730250/