简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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