简体   繁体   English

如何在Java中捕获异常?

[英]How to catch exception in Java?

I am getting following exception in my code and I want to catch the inner exception. 我在代码中遇到异常,我想捕获内部异常。 Is it possible to catch that? 有可能抓住吗?

java.lang.RuntimeException: error
some stack trace
some stack trace
some stack trace
! Caused by: java.util.concurrent.TimeoutException: null
some stack trace
some stack trace
some stack trace

Lets say I have following code. 可以说我有以下代码。

function abc() {
  try{
    xyz()
  } catch (TimeoutException e) {
     do stuff
  }
}

xyz() function is generating that exception. xyz()函数正在生成该异常。 Would catching the TimeoutException like this work? 会像这样工作捕获TimeoutException吗?

You can't do it directly. 您不能直接这样做。 You have to catch the outer exception, check its getCause() to see if it's what you want, and then either handle that cause or re-throw the top-level exception. 您必须捕获外部异常,检查其getCause()以查看是否是所需异常,然后处理导致该异常的原因或重新引发顶级异常。

(You could also technically re-throw just the inner one, but I would strongly discourage that; the stack trace will be very confusing, and it'll be harder to debug -- especially a year from now, when you've forgotten that you did that.) (从技术上讲,您也可以只抛出内部的,但是我强烈不建议这样做;堆栈跟踪将非常混乱,并且将更加难以调试-尤其是从现在开始的一年,当您忘记了你做到了)

No, you can't catch a RuntimeException with catch(TimeoutException e) . 不,您不能使用catch(TimeoutException e)捕获RuntimeException

However, you could do 但是,你可以做

} catch (RuntimeException e) {
  Throwable cause = e.getCause(); 
}

to get the cause. 得到原因。

You cannot directly catch a RuntimeException caused by a TimeoutException . 您不能直接捕获由TimeoutException引起的RuntimeException

But you achieve it like this: 但是您可以这样实现:

    try {
        xyz();
    } catch (RuntimeException e) {
        if (e.getCause() instanceof TimeoutException) {
            // handle TimeoutException
            doStuff();
        } else {
            // rethrow all exceptions with other causes
            throw e;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM