[英]How to throw exception
What are the best practices for choosing between throw;
选择throw;
之间的最佳做法是什么? and throw ex;
并throw ex;
? ? Is there any at all? 有没有? Regarding -for example- this simple snippet: 关于 - 例如 - 这个简单的片段:
try{
// some code
} catch (Exception ex) {
// some catcher code
// throw; ?
// or
// throw ex; ?
// how to decide which one?
}
UPDATE: I know the difference between the tow above. 更新:我知道上面的两个区别。 Question is how to decide to use one of them? 问题是如何决定使用其中之一? Is there any best practice to making a better choice? 有没有最好的做法来做出更好的选择?
You should either use throw;
你应该使用throw;
to re-throw the original exception (with the original stack trace) or use throw new MyException(..., ex);
重新抛出原始异常(使用原始堆栈跟踪)或使用throw new MyException(..., ex);
to throw your own exception that may provide additional information AND set inner exception to ex. 抛出你自己的异常,可以提供额外的信息并将内部异常设置为ex。
If you don't have any additional information just use throw;
如果您没有任何其他信息,请使用throw;
If you only catch the exception to do cleanup, then use try {...} finally {...}
instead. 如果您只捕获异常以进行清理,那么请使用try {...} finally {...}
。
Do you want to keep stack trace to see exactly where exception occurs? 您是否希望保持堆栈跟踪以准确查看异常发生的位置? Then use throw
, this will be like if you don't use catch
at all. 然后使用throw
,这就像你根本不使用catch
。
Do you only care about current method debug info? 您只关心当前的方法调试信息吗? Then throw ex
. 然后throw ex
。
To demonstrate: 展示:
static void Main(string[] args)
{
try
{
Test();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
static void Test()
{
try
{
// long lambda chain
new Action(() => new Action(() => new Action(() => { throw new InvalidOperationException(); })())())();
}
catch (Exception ex)
{
//throw;
//throw ex;
}
}
throw
will keep stack trace: throw
将保持堆栈跟踪:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at ConsoleApplication.Program.<>c.<Test>b__1_2() in ConsoleApplication\Program.cs:line 22
at ConsoleApplication.Program.<>c.<Test>b__1_1() in ConsoleApplication\Program.cs:line 22
at ConsoleApplication.Program.<>c.<Test>b__1_0() in ConsoleApplication\Program.cs:line 22
at ConsoleApplication.Program.Test() in ConsoleApplication\Program.cs:line 26
at ConsoleApplication.Program.Main(String[] args) in ConsoleApplication\Program.cs:line 13
throw ex
will reset stack trace: throw ex
将重置堆栈跟踪:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at ConsoleApplication.Program.Test() in ConsoleApplication\Program.cs:line 27
at ConsoleApplication.Program.Main(String[] args) in ConsoleApplication\Program.cs:line 13
As for best practices - the choice is usually throw
, as developer you want to get as much information as you can, throw ex
is a counterpart - some information is hidden, but maybe you want to hide it, who knows? 至于最佳实践 - 选择通常是throw
,作为开发人员,你想获得尽可能多的信息, throw ex
是对应的 - 一些信息是隐藏的,但也许你想隐藏它,谁知道?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.