Java: catching specific Exceptions

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

    My proposition - catch SQLException and check code.

    try {
        getConnectionSYS(dbConfigFile, properties);
    } catch (SQLException e){
        if (e.getErrorCode()==1017){
            getConnectionUSER(dbConfigFile, properties);
        } else {
            throw e;
        }
    }
    
    0 讨论(0)
  • 2021-01-07 22:13

    This won't compile. You'll be told that the specific exception block isn't reachable.

    You have to have the more specific exception catch block first, followed by the general one.

    try
    {
        //something
    } 
    catch(SpecificException se)
    {
        //catch specific exception only
    }
    catch(Exception generic)
    {
        //catch all
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 22:22

    This does not compile with eclipse compiler:

    Unreachable catch block for IOException. It is already handled by the catch block for Exception

    So define them the other way. Only the specific one will be caught.

    0 讨论(0)
  • 2021-01-07 22:23

    As a side note, the only way to have both catch blocks called is to use nested exceptions.

    try {
      try{
      //something
      }catch(SpecificException se){
      //catch specific exception only
      throw se;
      }
    }catch(Exception generic){
    //catch all
    }
    
    0 讨论(0)
提交回复
热议问题