This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
Question: Questions about exception handling
I have a question about exception handling. Consider the following Java code snippet.
try{
//code
}catch(SubSubException subsubex){
//code
}catch(SubException subex){
//code
}catch(Exception ex){
//code
}
Copy the code
I know this is the recommended way to handle exceptions. But I can achieve the same functionality by using the following code snippet.
try{
//code
}catch ( Exception ex){
if( ex instanceof SubException){
//code
}else if(ex instanceof SubSubException){
//code
}else{
//code}}Copy the code
Can someone tell me the disadvantages of the second method?
Answer a
The second method is less readable. Furthermore, Pokemon exception handling is never a good idea, even if your “smart” trick is to use the instanceof keyword. I’m not joking or mocking you, but it’s better to write code for humans to read and maintain than for computers.
Answer two
Yes, MadMurf points out the most important difference: compile-time reachability checks. Standard idioms catch such content and correctly prevent it from compiling
try{}catch (IndexOutOfBoundsException iooe) {
} catch (ArrayIndexOutOfBoundsException aiooe) {
}
Copy the code
The if/ Instanceoj proposed in the original problem will simulate compilation (which is not what you want, because it is wrong).
To further illustrate this point, the following documents have been prepared:
try{}catch (Exception e) {
if (e instanceof Exception) {
} else if (e instanceof Exception) {
}
}
Copy the code
As you can see, this “Pokemon-Catching” idiom is difficult to maintain because it bypasses some compile-time reachability checks that are enforced by standard conventions.
To make this point more clearly, whether intentionally or not, you actually rearrange the order in which you check the exceptions to the problem, a fact that is easily overlooked by others. If SubSubException is a subclass of SubException, then the second If condition will never be evaluated and its body will actually be inaccessible code.
The if/ Instanceof method is very error-prone.
Answer three
I want it to be more readable
try{... }catch (IndexOutOfBoundsException iooe) { }
catch (ArrayIndexOutOfBoundsException aiooe) { }
.....
Copy the code
and
try{... }catch (Exception e) {
if (e instanceof Exception) { } else
if (e instanceof Exception) { } else. }...Copy the code
The article translated from Stack Overflow:stackoverflow.com/questions/2…