Why does order matter when catching exceptions?

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

    In Java you have to put the least inclusive Exception first. The next exceptions must be more inclusive (when they are related).

    For instance: if you put the most inclusive of all (Exception) first, the next ones will never be called. Code like this:

    try {
         System.out.println("Trying to prove a point");
         throw new java.sql.SqlDataException("Where will I show up?");
    }catch(Exception e){
         System.out.println("First catch");
    } catch(java.sql.SQLException e) {
         System.out.println("Second catch");
    }
    catch(java.sql.SQLDataException e) {
         System.out.println("Third catch");
    }
    

    will never print the message you'd expect it to print.

提交回复
热议问题