抓住Throwable是不好的做法?赶上是不好的做法Throwable?例如这样的事情:try {
// Some code} catch(Throwable e) {
// handle the exception}这是一种不好的做法还是我们应该尽可能具体?
3 回答

陪伴而非守候
TA贡献1757条经验 获得超8个赞
这是一个坏主意。事实上,即使是捕捉Exception
通常也是一个坏主意。我们来看一个例子:
try { inputNumber = NumberFormat.getInstance().formatNumber( getUserInput() );} catch(Throwable e) { inputNumber = 10; //Default, user did not enter valid number}
现在,假设getUserInput()阻塞了一段时间,另一个线程以最坏的方式阻止你的线程(它调用thread.stop())。你的catch块会遇到ThreadDeath
错误。这太糟糕了。捕获该异常后代码的行为很大程度上是未定义的。
捕获异常会出现类似的问题。可能getUserInput()
因InterruptException或尝试记录结果时出现权限被拒绝异常或其他各种故障而失败。你不知道出了什么问题,因为那样,你也不知道如何解决这个问题。
你有三个更好的选择:
1 - 准确捕获您知道如何处理的异常:
try { inputNumber = NumberFormat.getInstance().formatNumber( getUserInput() );} catch(ParseException e) { inputNumber = 10; //Default, user did not enter valid number}
2 - 重新抛出遇到的任何异常,并且不知道如何处理:
try { doSomethingMysterious();} catch(Exception e) { log.error("Oh man, something bad and mysterious happened",e); throw e;}
3 - 使用finally块,这样您就不必记住重新抛出:
Resources r = null; try { r = allocateSomeResources(); doSomething(r); } finally { if(r!=null) cleanUpResources(r); }

沧海一幻觉
TA贡献1824条经验 获得超5个赞
另外请注意,当您捕获时Throwable
,您还可以捕获InterruptedException
哪些需要特殊处理。有关更多详细信息,请参阅处理InterruptedException。
如果您只想捕获未经检查的异常,则可能还会考虑此模式
try { ...} catch (RuntimeException exception) { //do something} catch (Error error) { //do something}
这样,当您修改代码并添加可以抛出已检查异常的方法调用时,编译器会提醒您,然后您可以决定如何处理此情况。
添加回答
举报
0/150
提交
取消