Why use IOexception instead of Exception when catching?

后端 未结 3 527
别那么骄傲
别那么骄傲 2020-12-18 03:36

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         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 04:15

    As a followup to dkatzel's answer, let's assume you start to read from the file in the same try block and the file tells you which value in a array of options to use:

    String toPrint = {"Hi", "World", "I'm", "A", "String", "Array"};
    try{
        BufferedReader reader = new BufferedReader( new FileReader("foo.bar") );
        String line = reader.readLine();
        System.out.println(toPrint[Integer.parseInt(line)]);
    
    }
    catch(Exception e){
        println( e.getMessage() );
    }
    

    Now you have absolutely no idea what really went wrong except through the stack trace. You can't handle any fixable problems. You can't tell in code whether the file doesn't exist (FileNotFoundException), you don't have access to the file, (IOException), if the first line wasn't an Integer (NumberFormatException), or the number was bigger than the array length (ArrayIndexOutOfBoundsException). If you wanted to print a default value if you couldn't read the number, you could instead catch a NumberFormatException and print the value instead of having to quit the entire program.

    I'll admit this is a pretty contrived example, but it should give you an explanation of why catching Exception is bad. Marko also has a very good answer, stating that it usually is better to let the exception propagate up (especially with RuntimeExceptions) than to create a bunch of messy code trying to deal with every single problem that can happen.

提交回复
热议问题