捕获时为什么要使用IOexception而不是Exception? [英] Why use IOexception instead of Exception when catching?

查看:110
本文介绍了捕获时为什么要使用IOexception而不是Exception?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法正确地说明这一点,搜索引擎可以获得任何有意义的结果。

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

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

仅限 FileReader 抛出 FileNotFoundException ,据我所知它是一个 IOException ,这是一个异常。有人可以解释为什么我会捕获 FileNotFoundException IOException 而不是只指定泛型Exception而不必导入异常(即import java.io.FileNotFoundException;)?它是否仅仅是为了可读性?

So FileReader only throws the FileNotFoundException, which as I understand it is an IOException, which is an Exception. Can someone explain why I would catch FileNotFoundException or IOException instead of just specifying the generic "Exception" and not having to import an exception (i.e. import java.io.FileNotFoundException;)? Is it strictly for readability?

我使用所有三个名称捕获了异常,我找不到区别。

I've caught the exception using all three names and I can't find a difference.

编辑:--------------------

--------------------

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;
    }


推荐答案

异常是所有异常的母亲,包括所有 RuntimeException 子类。当您指定捕获它时,您将获得比您想要的更多的鱼,例如 NullPointerException s, IllegalArgumentException s等等。

Exception is the mother of all exceptions, including all RuntimeException subclasses. When you specify to catch it, you'll get much more fish in the net than you wanted, like NullPointerExceptions, IllegalArgumentExceptions and so on.

虽然捕获通用异常 的权利在你的代码中的某些方面做的事情,在任何较低层捕获它几乎肯定是错误的并且可能会损害你的应用程序的行为。

While catching the generic Exception is the right thing to do at some point in your code, catching it at any lower layer is almost certainly wrong and can hurt the behavior of your application.

学习更重要的技能在Java中不是如何捕获异常,而是如何不捕获它们,而是让它们向上传播调用堆栈,朝向异常障碍,这是一个常见的点。代码,其中捕获并统一处理所有错误(通常通过记录,回滚事务等)。

The more important skill to learn in Java is not how to catch exceptions, but how to not catch them, instead letting them propagate up the call stack, towards the exception barrier, the one common spot in the code where all errors are caught and uniformly handled (typically by logging, rolling back the transaction, and similar).

这篇关于捕获时为什么要使用IOexception而不是Exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆