Java: catching specific Exceptions

后端 未结 6 1356
迷失自我
迷失自我 2021-01-07 21:17

say I have the following

try{
//something
}catch(Exception generic){
//catch all
}catch(SpecificException se){
//catch specific exception only
}
6条回答
  •  花落未央
    2021-01-07 22:18

    The catch blocks are tried in order, and the first one that matches the type of the exception is executed. Since Exception is the superclass of all exception types, it will always be executed in this instance and the specific cases will never be executed. In fact the compiler is smart enough to notice this and raise a compilation error.

    Just reorder the catch clauses.

提交回复
热议问题