Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is multi-catch implemented in Java 7?

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 ?

like image 966
Deepak Avatar asked Apr 24 '12 15:04

Deepak


2 Answers

Based on the Java Virtual Machine Specification, exceptions are compiled as follows (in summary):

  • try code is run normally
  • each catch block is compiled as if it were a separate method
  • there is an exception table to redirect the execution flow to the right catch block

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
like image 123
assylias Avatar answered Nov 16 '22 00:11

assylias


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)

like image 31
Denys Séguret Avatar answered Nov 16 '22 00:11

Denys Séguret