我一直相信,如果一个方法可以抛出异常,那么不使用有意义的try块来保护这个调用就是鲁莽的。

我刚刚发布了‘你应该总是包装调用,可以抛出try, catch块。,结果被告知这是一个“非常糟糕的建议”——我想知道为什么。


当前回答

方法应该只在能够以某种合理的方式处理异常时才捕获异常。

否则,将其向上传递,希望调用堆栈中更高位置的方法能够理解它。

正如其他人所注意到的,在调用堆栈的最高级别上使用一个未处理的异常处理程序(带有日志记录)是一种良好的实践,以确保记录任何致命错误。

其他回答

尽管Mike Wheat的回答很好地总结了要点,但我还是觉得有必要再补充一个答案。我是这样想的。当你有方法做很多事情时,你是在增加复杂性,而不是增加它。

换句话说,封装在try catch中的方法有两种可能的结果。有非异常结果和异常结果。当你处理很多方法的时候这个指数级的爆炸超出了你的理解。

因为如果每个方法都以两种不同的方式分支,那么每次调用另一个方法时,你都是在对之前的潜在结果数进行平方。当你调用了5个方法时,你至少有256个可能的结果。与此相比,在每个方法中都不执行try/catch,您只有一条路径可以遵循。

我基本上就是这么看的。您可能会认为任何类型的分支都做同样的事情,但try/catch是一个特殊情况,因为应用程序的状态基本上是未定义的。

简而言之,try/catch使代码更难理解。

我想在这个讨论中补充一点,自从c++ 11以来,它确实很有意义,只要每个catch块重新抛出异常,直到它可以/应该被处理为止。通过这种方式可以生成反向跟踪。因此,我认为前面的观点在某种程度上已经过时了。

使用std::nested_exception和std::throw_with_nested

在这里和这里的StackOverflow描述了如何实现这一点。

由于可以对任何派生异常类执行此操作,因此可以向这样的回溯添加大量信息! 你也可以看看我在GitHub上的MWE,在那里回溯看起来是这样的:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

As Mitch and others stated, you shouldn't catch an exception that you do not plan on handling in some way. You should consider how the application is going to systematically handle exceptions when you are designing it. This usually leads to having layers of error handling based on the abstractions - for example, you handle all SQL-related errors in your data access code so that the part of the application that is interacting with domain objects is not exposed to the fact that there is a DB under the hood somewhere.

除了“在任何地方捕获所有东西”的味道之外,还有一些相关的代码味道是您一定要避免的。

"catch, log, rethrow": if you want scoped based logging, then write a class that emits a log statement in its destructor when the stack is unrolling due to an exception (ala std::uncaught_exception()). All that you need to do is declare a logging instance in the scope that you are interested in and, voila, you have logging and no unnecessary try/catch logic. "catch, throw translated": this usually points to an abstraction problem. Unless you are implementing a federated solution where you are translating several specific exceptions into one more generic one, you probably have an unnecessary layer of abstraction... and don't say that "I might need it tomorrow". "catch, cleanup, rethrow": this is one of my pet-peeves. If you see a lot of this, then you should apply Resource Acquisition is Initialization techniques and place the cleanup portion in the destructor of a janitor object instance.

我认为充斥着try/catch块的代码是代码评审和重构的好目标。它表明要么异常处理没有被很好地理解,要么代码已经变成了无用的,急需重构。

如果您想测试每个函数的结果,请使用返回码。

exception的目的是为了降低测试结果的频率。其思想是将异常(不寻常的,罕见的)条件从更普通的代码中分离出来。这使得普通代码更简洁,但仍然能够处理那些异常情况。

在设计良好的代码中,较深的函数可能会抛出,较高级的函数可能会捕获。但关键是,许多“介于两者之间”的功能将完全摆脱处理异常情况的负担。它们只需要是“异常安全的”,这并不意味着它们必须捕获。

我的计算机科学教授曾经给我的建议是:“只有在使用标准方法无法处理错误时,才使用Try and Catch块。”

作为一个例子,他告诉我们,如果一个程序在一个地方遇到了一些严重的问题,而不可能做这样的事情:

int f()
{
    // Do stuff

    if (condition == false)
        return -1;
    return 0;
}

int condition = f();

if (f != 0)
{
    // handle error
}

然后你应该使用try, catch块。虽然您可以使用异常来处理这个问题,但通常不建议这样做,因为异常会消耗大量性能。