Why does order matter when catching exceptions?

前端 未结 8 1306
闹比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:47

    For compiler multiple catch statements are like if..else if..else if..

    So, from the point where compiler can map the generated exception (directly or by implicit type conversion), it will not execute subsequent catch statements.

    To avoid this implicit type conversion you should keep the more generic exception at last. More derived should be stated at the beginning of he catch statements and most generic should go at the last catch statements.

    SQLDataException is derived from SQLException which is interns deiced from Exception. So, you will not be able to execute any code written in catch(java.sql.SQLDataException e){} this block. Compiler even flags for that situation that its a dead code and will not be executed.

提交回复
热议问题