Java: catching specific Exceptions

后端 未结 6 1400
迷失自我
迷失自我 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:17

    No. All exceptions would be caught by the first block. The second will never be reached (which the compiler recognizes, leading to an error due to unreachable code). If you want to treat SpecificException specifically, you have to do it the other way round:

    }catch(SpecificException se){
    //catch specific exception only
    }catch(Exception generic){
    //catch all
    }
    

    Then SpecificException will be caught by the first block, and all others by the second.

提交回复
热议问题