捕获和重新抛出 .NET 异常的最佳实践 [英] Best practices for catching and re-throwing .NET exceptions

查看:32
本文介绍了捕获和重新抛出 .NET 异常的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

捕获异常并重新抛出异常时要考虑的最佳实践是什么?我想确保保留 Exception 对象的 InnerException 和堆栈跟踪.以下代码块在处理这个问题的方式上有区别吗?

试试{//一些代码}捕获(异常前){扔前;}

对比:

试试{//一些代码}抓住{扔;}

解决方案

保留堆栈跟踪的方法是通过使用 throw; 这也是有效的

尝试{//在这里爆炸的东西捕获(异常前){扔;}

throw ex; 基本上就像从那个点抛出异常,所以堆栈跟踪只会到你发出 throw ex; 语句的地方.>

Mike 也是正确的,假设异常允许您传递例外(推荐).

Karl Seguin 有一个 在他的 基础编程电子书 也是很好的读物.

编程基础 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 the way they handle this?

try
{
    //some code
}
catch (Exception ex)
{
    throw ex;
}

Vs:

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 bombs 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".

这篇关于捕获和重新抛出 .NET 异常的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆