How is the Java 7 compiler handling multi-catch blocks ? A naive implementation would be to generate bytecode as if multiple catch blocks are present. However, I have gathered from multiple source that this is not the case - A catch block that handles multiple exception types contributes no duplicate bytecode during compilation.
So, how does it work ? Is there a new bytecode instruction that tells the JVM about multi-catch blocks ?
Based on the Java Virtual Machine Specification, exceptions are compiled as follows (in summary):
When using a multi catch clause, the catch block is the same (appears only once), but the exception table will contain one more entry with the same from, to and target values.
For example, this code:
public static void main(String args[]) throws InterruptedException {
try {
System.out.println("why not?");
} catch (IllegalArgumentException e) {
System.out.println("here");
} catch (IllegalStateException | ArithmeticException e) {
System.out.println("there");
}
}
generates the following exception table (on my machine):
from to target type
0 8 11 Class java/lang/IllegalArgumentException
0 8 23 Class java/lang/IllegalStateException
0 8 23 Class java/lang/ArithmeticException
The exception table works like a kind of switch iterating over all exception classes, (entries in the exception table) and checking if the throwed exception implements it, thus deciding where to jump in the bytecode.
http://www.artima.com/underthehood/exceptions.html
According to this, you just have to make a new entry in the exception table and I don't see why two entries couldn't just point to the same pc offset.
(disclaimer : I'm no expert in bytecode, haven't touched one in years and so may miss something)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With