【发布时间】:2009-12-02 21:02:30
【问题描述】:
我目前正在维护一段有点“异常快乐”的代码。基本上,任何方法或任何东西都会抛出异常。我将努力解决这个问题,但与此同时,我想知道在较小的代码块(例如方法)中处理单个异常的最佳方法是什么。这样做更好吗:
public void aMethod()
try {
//Lots of code in here. Many lines.
} catch(Exception e) {
// TODO - Handle All Exceptions, but fairly generically
}
}
或者是这样的:
public void bMethod() {
try {
// One line of code.
} catch(Exception e) {
// TODO - Handle a specific Exception (may even involve rethrowing it with more information)
}
// More code.
try {
// Another line of code.
} catch(Exception e) {
// TODO - Handle another specific exception.
}
}
我意识到这是一个非常基本的问题,但是在查看了数百种方法后,每个方法都会出现异常,我开始想知道如何最好地处理所有这些方法以及这里的最佳实践可能是什么。
【问题讨论】:
标签: java exception exception-handling methods