.jpg)
有一些帖子询问这两者之间的区别已经是什么。
(为什么我什至必须提到这个…
但我的问题有所不同,我在另一种错误神一样的处理方法中称之为“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 & catchMainthrow;HandleException
是否与在内部调用时调用具有相同的效果?throw ex;throwHandleException

是的,有区别。
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;
}
}

(我之前发过,@Marc Gravell 纠正了我)
以下是差异的演示:
static void Main(string[] args) {
try {
ThrowException1(); // line 19
} catch (Exception x) {
Console.WriteLine("Exception 1:");
Console.WriteLine(x.StackTrace);
}
try {
ThrowException2(); // line 25
} catch (Exception x) {
Console.WriteLine("Exception 2:");
Console.WriteLine(x.StackTrace);
}
}
private static void ThrowException1() {
try {
DivByZero(); // line 34
} catch {
throw; // line 36
}
}
private static void ThrowException2() {
try {
DivByZero(); // line 41
} catch (Exception ex) {
throw ex; // line 43
}
}
private static void DivByZero() {
int x = 0;
int y = 1 / x; // line 49
}
这是输出:
Exception 1:
at UnitTester.Program.DivByZero() in <snip>DevUnitTesterProgram.cs:line 49
at UnitTester.Program.ThrowException1() in <snip>DevUnitTesterProgram.cs:line 36
at UnitTester.Program.TestExceptions() in <snip>DevUnitTesterProgram.cs:line 19
Exception 2:
at UnitTester.Program.ThrowException2() in <snip>DevUnitTesterProgram.cs:line 43
at UnitTester.Program.TestExceptions() in <snip>DevUnitTesterProgram.cs:line 25
可以看到,在异常 1 中,堆栈跟踪返回到方法,而在异常 2 中则不会。DivByZero()
但是请注意,中显示的行号是语句的行号,而不是调用的行号,现在我想了一下,这可能是有道理的……ThrowException1()ThrowException2()throwDivByZero()
例外 1:
at ConsoleAppBasics.Program.ThrowException1()
at ConsoleAppBasics.Program.Main(String[] args)
例外 2:
at ConsoleAppBasics.Program.ThrowException2()
at ConsoleAppBasics.Program.Main(String[] args)
它是否仅在调试模式下维护原始堆栈跟踪?

抛出保留堆栈跟踪。因此,假设 Source1 抛出错误 1,它被源 2 捕获,源 2 说抛出,然后源 1 错误 + 源 2 错误将在堆栈跟踪中可用。
抛出 ex 不会保留堆栈跟踪。因此,Source1 的所有错误都将被清除,只有 Source2 错误将发送到客户端。
有时只是阅读内容不清楚,建议观看此视频演示以获得更清晰的信息,在C#中投掷与抛出ex。

模板简介:该模板名称为【“throw” 和 “throw ex”有什么区别?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。