Why use IOexception instead of Exception when catching?

后端 未结 6 916
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 03:31

I can\'t seem to phrase this correctly for the search engine to pick up any meaningful results.

try{
    BufferedReader reader = new BufferedReader( new File         


        
6条回答
  •  鱼传尺愫
    2020-12-18 04:11

    FileNotFoundException is an IOException which is an Exception

    You are right. But if you catch Exception objects you will catch any exception triggered by your code, not only the FileNotFound exception.

    Let's say that your code can throw more than one kind of exception:

    try {
        /*
         * Code, code and more code
         */
    } catch(ExceptionType1 e) {
            System.err.println("Something went wrong! It is a type 1 exception");
    } catch(ExceptionType2 e) {
            System.err.println("Something went wrong! It is a type 2 exception");
    } catch(Exception e) {
            System.err.println("Something went wrong! It is not any of the known exception types");
    }
    

    Compare the above possibility with this:

    try {
        /*
         * Code, code and more code
         */
    } catch(Exception e) {
            System.err.println("Something went wrong! Can be exception type 1, 2 or something else");
    }
    

    As you can see, differentiating the exception types can help you understand what went wrong in your code.

提交回复
热议问题