引发异常的最佳实践 [英] Throwing Exceptions best practices
问题描述
什么是捕获异常,并重新抛出它们时需要考虑的最佳实践?我想确保异常对象的InnerException和堆栈跟踪是preserved。有没有在如何处理这种情况下code块之间的区别是什么?
尝试
{
//一些code
}
赶上(例外前)
{
抛出前;
}
// ......
尝试
{
//一些code
}
抓住
{
扔;
}
的方式preserve堆栈跟踪是通过使用的扔;
这是也有效
尝试{
//东西,物料清单在这里
}赶上(例外前)
{
扔;
}
罚球前;
基本上是想从该点抛出一个异常,所以堆栈跟踪只会去你在哪里发出掷前;
语句
<一个href="http://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649">Mike也是正确的,假定除允许你传递一个例外(推荐)。
卡尔·塞甘有一个<一个href="http://$c$cbetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx">great写上异常处理在他的编程电子书的基础为好,这是一个伟大的阅读。
编辑:工作链接 PDF href="http://openmymind.net/FoundationsOfProgramming.pdf">基础。只是搜索的文本为异常。
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in how they handle this?
try
{
//some code
}
catch (Exception ex)
{
throw ex;
}
//......
try
{
//some code
}
catch
{
throw;
}
The way to preserve the stack trace is through the use of the throw;
This is valid as well
try {
// something that boms here
} catch (Exception ex)
{
throw;
}
throw ex;
is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex;
statement
Mike is also correct, assuming the exception allows you to pass an exception (which is recommended).
Karl Seguin has a great write up on exception handling in his foundations of programming e-book as well, which is a great read.
Edit: Working link to Foundations of Programming pdf. Just search the text for "exception".
这篇关于引发异常的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!