Why does order matter when catching exceptions?

前端 未结 8 1334
闹比i
闹比i 2020-11-29 09:52

I had to answer this question with some code:

Suppose I wrote the following method specification:
public void manipulateData ( ) t

8条回答
  •  广开言路
    2020-11-29 10:52

    When exception happens in the method, a special method exception table is checked, it contains records for each catch block: exception type, start instruction and end instruction. If the order of exception is incorrect, some catch block would be unreachable. Sure javac could sort records in this table for developer, but it does not.

    JVM Specification: 1 and 2

    The order in which the exception handlers of a method are searched for a match is important. Within a class file, the exception handlers for each method are stored in a table (§4.7.3). At run time, when an exception is thrown, the Java Virtual Machine searches the exception handlers of the current method in the order that they appear in the corresponding exception handler table in the class file, starting from the beginning of that table.

    As long as first exception is a parent of the second, the second block becomes unreacheble.

提交回复
热议问题