简体   繁体   English

即使在catch块中捕获了异常对象之后,我们还能将异常对象扔给调用方法吗?

[英]can we throw the exception object to calling method even after catching it in the catch block?

Consider a sample code: 考虑一个示例代码:

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");
    }
}

So is something like this possible? 那有可能这样吗? if yes then how, what is to be out in place of "something here to throw to the calling method, to manage the Exception"... 如果是的话,怎么办呢,而不是“这里的东西要扔给调用方法,以管理异常”。

IE my question is can we conditionally manage like this , that we want to handle the exception here or not. IE我的问题是我们可以像这样有条件地进行管理,我们是否要在这里处理异常。

Sure, you can throw in your catch block no problem. 当然,您可以毫无问题地放入捕获块。 You can even layer in your own useful exception and maintain your exception causal chain using the 您甚至可以使用自己的有用异常进行分层,并使用

Throwable(String message, Throwable cause)

constructor. 构造函数。 For example let's say you had a special RetryLimitReachedException , you could toss it out like so 例如,假设您有一个特殊的RetryLimitReachedException ,您可以像这样扔掉它

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

In your stacktrace you'll be able to clearly see that this class was unable to handle it, and so passed it back up. 在您的堆栈跟踪中,您将能够清楚地看到此类无法处理它,因此将其传递回去。 And you'll be able to see what exactly caused the unhandleable exception condition in the Caused By. . . 然后,您将能够在Caused By. . .查看到底是什么导致了无法处理的异常情况Caused By. . . Caused By. . . line(s) of the stacktrace. 堆栈跟踪的行。

Sure, you can just rethrow the exception you catch: 当然,您可以重新抛出捕获的异常:

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
   }
}

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

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