为什么在C#中捕获并重新抛出异常

为什么在C#中捕获并重新抛出异常

本文介绍了为什么在C#中捕获并重新抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看文章 似乎支持我的争论,try-catch-throw是一个no-op。

The Stack Overflow question The difference between re-throwing parameter-less catch and not doing anything? seems to support my contention that try-catch-throw is-a no-op.

编辑:

只是总结一下找到这个未来的线程...

Just to summarise for anyone who finds this thread in future...

不要

try {
    // Do stuff that might throw an exception
}
catch (Exception e) {
    throw e; // This destroys the strack trace information!
}

堆栈跟踪信息对于识别问题的根本原因至关重要!

The stack trace information can be crucial to identifying the root cause of the problem!

DO

try {
    // Do stuff that might throw an exception
}
catch (SqlException e) {
    // Log it
    if (e.ErrorCode != NO_ROW_ERROR) { // filter out NoDataFound.
        // Do special cleanup, like maybe closing the "dirty" database connection.
        throw; // This preserves the stack trace
    }
}
catch (IOException e) {
    // Log it
    throw;
}
catch (Exception e) {
    // Log it
    throw new DAOException("Excrement occurred", e); // wrapped & chained exceptions (just like java).
}
finally {
    // Normal clean goes here (like closing open files).
}

在较不具体的异常之前捕获更具体的异常(就像Java一样)。

Catch the more specific exceptions before the less specific ones (just like Java).

参考资料:

  • MSDN - Exception Handling
  • MSDN - try-catch (C# Reference)

推荐答案

文章中的代码的方式是邪恶的。 throw ex 将将异常中的调用堆栈重置为此throw语句的点;丢失有关创建异常的信息。

First; the way that the code in the article does it is evil. throw ex will reset the call stack in the exception to the point where this throw statement is; losing the information about where the exception actually was created.

其次,如果你只是抓住并重新抛出,我看不到附加值,上面的代码示例(或者,给定 throw ex bit,甚至更好)没有try-catch。

Second, if you just catch and re-throw like that, I see no added value, the code example above would be just as good (or, given the throw ex bit, even better) without the try-catch.

但是,有些情况下您可能希望捕获和重新抛出异常。记录可能是其中之一:

However, there are cases where you might want to catch and rethrow an exception. Logging could be one of them:

try
{
    // code that may throw exceptions
}
catch(Exception ex)
{
    // add error logging here
    throw;
}

这篇关于为什么在C#中捕获并重新抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:21