简体   繁体   中英

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 ?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM