Reputation: 550
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"...
I.E. my question is can we conditionally manage like this , that we want to handle the exception here or not.
Upvotes: 0
Views: 78
Reputation: 7573
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. . .
line(s) of the stacktrace.
Upvotes: 3
Reputation: 312136
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
}
}
Upvotes: 1