Reputation: 1002
Today i stumbled upon this piece of code
try {
...
} catch (Exception e) {
if (e instanceof Exception) {
...
} else {
...
}
}
Does the if-else branching make any sense? Wouldn't caught Exception e
always be an instance of Exception
?
Upvotes: 3
Views: 5450
Reputation: 88747
Yes e
would always be an instanceof Exception
. As such the code you posted wouldn't make much sense.
Even if you'd want to handle different exceptions you'd rather do one of the following (example):
catch( IOException e) {
//handle IOExceptions
}
catch( MyUserException e) {
//handle user exceptions
}
... //any other exceptions you want to handle
If you want to handle some exceptions in the same way as of Java 7 you'd do something like this:
catch( IOException | MyUserException e) {
//same handling for both
}
Prior to Java 7 you might encounter situations where you see catch( Exception e)
and instanceof
checks inside the catch-block but one should be careful with such constructs and if you have better options (i.e. Java 7+ multi-catch) you should consider those.
Finally note that a catch-all expression like catch(Exception e)
can be useful but it can also be a source for errors, especially if the handling is poor. In most cases you want to handle expected exceptions in a specific way (e.g. IOExceptions) and let all others bubble up. Of course your code might want to catch all uncaught exceptions at some point (e.g. to log them) and that's where you'd use catch(Exception e)
- but you should be aware of the implications and what to do in those cases.
Upvotes: 10
Reputation: 921
The code above would not make any sense as e would always be an object(instance) of exception class.So to be more clear the program control will never enter else block as if(e instanceof Exception) will always e true.
Upvotes: 0