How is multi-catch implemented in Java 7?

≡放荡痞女 提交于 2019-12-03 11:25:08

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!