我一直相信,如果一个方法可以抛出异常,那么不使用有意义的try块来保护这个调用就是鲁莽的。
我刚刚发布了‘你应该总是包装调用,可以抛出try, catch块。,结果被告知这是一个“非常糟糕的建议”——我想知道为什么。
我一直相信,如果一个方法可以抛出异常,那么不使用有意义的try块来保护这个调用就是鲁莽的。
我刚刚发布了‘你应该总是包装调用,可以抛出try, catch块。,结果被告知这是一个“非常糟糕的建议”——我想知道为什么。
当前回答
如果总是在可能抛出异常的方法的调用者中立即处理异常,那么异常就变得毫无用处,最好使用错误代码。
异常的全部意义在于,不需要在调用链中的每个方法中处理它们。
其他回答
方法应该只在能够以某种合理的方式处理异常时才捕获异常。
否则,将其向上传递,希望调用堆栈中更高位置的方法能够理解它。
正如其他人所注意到的,在调用堆栈的最高级别上使用一个未处理的异常处理程序(带有日志记录)是一种良好的实践,以确保记录任何致命错误。
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块的代码是代码评审和重构的好目标。它表明要么异常处理没有被很好地理解,要么代码已经变成了无用的,急需重构。
我同意你的问题的基本方向,即在最低级别处理尽可能多的异常。
一些现有的回答是这样的:“您不需要处理异常。别人会在上面做的。”根据我的经验,这是一个不考虑当前开发的代码段异常处理的糟糕借口,让异常处理其他人或以后的问题。
在分布式开发中,这个问题会急剧增加,在分布式开发中,您可能需要调用由同事实现的方法。然后,您必须检查嵌套的方法调用链,以找出他/她为什么向您抛出一些异常,这在嵌套最深的方法中可以更容易地处理。
如果总是在可能抛出异常的方法的调用者中立即处理异常,那么异常就变得毫无用处,最好使用错误代码。
异常的全部意义在于,不需要在调用链中的每个方法中处理它们。
因为下一个问题是“我已经捕获了一个异常,接下来我该做什么?”你会怎么做?如果你什么都不做——这是错误隐藏,程序可能“就是不能工作”,没有任何机会发现发生了什么。您需要了解捕获异常后要做什么,并且只有在知道的情况下才进行捕获。