就像我有这两个场景我们必须处理FileNotFoundException
情况1:
try { FileInputStream fis = new FileInputStream("test1.txt"); } catch (FileNotFoundException e) { e.printstacktrace(); }
案例2:
try { FileInputStream fis = new FileInputStream("test1.txt"); } catch (Exception e) { e.printstacktrace(); }
解决方法
从
docs开始,它给出了原因:
“A subclass inherits all the members (fields,methods,and nested
classes) from its superclass. Constructors are not members,so they
are not inherited by subclasses,but the constructor of the superclass
can be invoked from the subclass.”
Exception类是所有其他异常类的父级.因此,如果您知道要获取FileNotFoundException,那么最好使用该异常.制作例外是一个通用的电话.
这有助于您理解:
因此,您可以看到Exception类处于更高层次结构,因此它意味着它将捕获除FileIOExcetion之外的任何异常.但是,如果要确保尝试打开由指定路径名表示的文件失败,则必须使用FileIOExcetion.
try { // Lets say you want to open a file from its file name. } catch (FileNotFoundException e) { // here you can indicate that the user specified a file which doesn't exist. // May be you can try to reopen file selection dialog Box. } catch (IOException e) { // Here you can indicate that the file cannot be opened. }
而相应的:
try { // Lets say you want to open a file from its file name. } catch (Exception e) { // indicate that something was wrong // display the exception's "reason" string. }