Why does order matter when catching exceptions?

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

    Order matter when catching exceptions because of following reason:

    Remember:

    • A base class variable can also reference child class object.
    • e is a reference variable
    catch(ExceptionType e){
    }
    

    The lowercase character e is a reference to the thrown (and caught) ExceptionType object.

    Reason why your code not accepted?

    It is important to remember that exception subclass must come before any their superclasses. This is because a catch statement that uses a superclasses will catch exception of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass.
    Further, in Java, Unreachable code is an error.

    SQLException is supperclass of SQLDataException

       +----+----+----+
       | SQLException |  `e` can reference SQLException as well as SQLDataException
       +----+----+----+
              ^
              |
              |
    +----+----+----+---+
    | SQLDataException |   More specific 
    +----+----+----+---+
    

    And if your write like having error Unreachable code (read comments):

    try{
    
    } 
    catch(java.sql.SQLException e){//also catch exception of SQLDataException type 
    
    }
    catch(java.sql.SQLDataException e){//hence this remains Unreachable code
    
    }
    

    If you try to compile this program, you will receive an error message stating that the first catch statement will handle all SQLException-based errors, including SQLDataException. This means that the second catch statement will never execute.

    Correct Solution?

    To fix it reverse the order of the catch statements.That is following:

    try{
    
    } 
    catch(java.sql.SQLDataException e){
    
    }catch(java.sql.SQLException e){
    
    }
    

提交回复
热议问题