我可以将异常对象抛出到调用方法,即使在catch块中捕获它之后?

时间:2016-09-13 21:38:58

标签: java exception exception-handling

考虑一个示例代码:

public void someMethod() throws Exception{
    try{
        int x = 5/0; //say, or we can have any exception here
    }
    catch(Exception e){
       if(counter >5){ // or any condition that depends on runtime inputs
       //something here to throw to the calling method, to manage the Exception
       }
       else
       System.out.println("Exception Handled here only");
    }
}

这样的事情可能吗?如果是,那么如何,取而代之的是“在这里抛出调用方法,管理异常”......

即。我的问题是我们可以有条件地管理这样的事情,我们想要处理这里的例外与否。

2 个答案:

答案 0 :(得分:3)

当然,你可以扔掉你的拦截块没问题。您甚至可以在自己的有用异常中进行分层,并使用

维护异常因果链
Throwable(String message, Throwable cause)

构造。例如,假设您有一个特殊的RetryLimitReachedException,您可以像这样抛弃它

catch (Exception e) {
  if (counter > 5) {
    throw new RetryLimitReachedException("Failed to do X, retried 5 times", e);
  }
....
}

在你的堆栈跟踪中,你将能够清楚地看到这个类无法处理它,因此将其传递回来。并且您将能够看到在堆栈跟踪的Caused By. . .行中究竟是什么造成了不可处理的异常情况。

答案 1 :(得分:1)

当然,你可以重新抛出你抓到的例外:

catch (Exception e) {
   if (counter > 5) {
       throw e; // Rethrow the exception
   }
   else {
       System.out.println("Exception Handled here only"); 
       // Or something more meaningful, for that matter
   }
}