【问题标题】:Is it the best practice to catch thowrable? [duplicate]捕捉 throwrable 是最佳做法吗? [复制]
【发布时间】:2012-06-17 02:55:20
【问题描述】:

可能重复:
Is it a bad practice to catch the Throwable?

捕捉可投掷物是最佳做法吗?如果捕获 throwable,它会捕获内存不足等异常吗?

【问题讨论】:

标签: java


【解决方案1】:

捕获Throwable 异常的唯一方法与捕获异常相同。它的工作原理是,它通过层次结构树捕获异常/错误。

因此,如果您想捕获 OutOfMemory 错误,您有一些选择:

try{
}catch(java.lang.OutOfMemoryError t){
}

try{
}catch(java.lang.Error t){
}

try{
}catch(java.lang.Throwable t){
}

只需检查文档中的类树以了解您想要捕获的异常。 http://docs.oracle.com/javase/6/docs/api/java/lang/OutOfMemoryError.html

还有一个很好的做法是,在你的 catch 块中,总是从树底部带有 are 的块开始,例如:

try{
//
}catch(java.lang.OutOfMemoryError t){
// handle out of memory error
}catch(java.lang.Throwable t){
// handle other throwable
}

还要记住,Error 和 Exception 它们都扩展 Throwable,但它们不相互扩展,所以它们都是类树中的兄弟。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多