Java – why use IOException instead of exception when capturing?

I can't seem to say this correctly. Search engines can get any meaningful results

try{
    BufferedReader reader = new BufferedReader( new FileReader("foo.bar") );
}
catch(Exception e){
    println( e.getMessage() );
}

So FileReader only throws FileNotFoundException. As far as I know, it is an IOException, which is an exception Can someone explain why I catch FileNotFoundException or IOException instead of specifying only the generic "exception" without importing the exception (that is, import Java. Io. FileNotFoundException;)? Is it strictly for readability?

I caught exceptions using all three names, and I couldn't find the difference

Edit: –––––––––––

private BufferedReader askUserForFile(String prompt){
        BufferedReader rd = null;
        while(rd == null){
            try{
                String filename = readLine(prompt);
                rd = new BufferedReader( new FileReader(filename) );
            }
            catch(Exception e){
                println(e.getMessage());
            }
        }
        return rd;
    }

Solution

Exceptions are the mother of all exceptions, including all runtimeException subclasses When you specify to capture it, you will get more fish in the network than you want, such as nullpointerexceptions, illegalargumentexceptions and so on

Although it is correct to catch a generic exception at some point in the code, it is almost certainly wrong to catch it at any lower level and may damage the behavior of the application

The more important skill learned in Java is not how to catch exceptions, but how to catch them, rather than let them propagate up the call stack, towards exception obstacles, a common location in the code, and all errors are captured and handled uniformly (usually through recording, rolling back transactions, etc.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>