繁体   English   中英

如何捕获通过读取和写入文件而抛出的所有异常?

[英]How can I catch all the exceptions that will be thrown through reading and writing a file?

在Java中,有没有办法获取(捕获)所有exceptions而不是单独捕获异常?

如果需要,可以向方法添加throws子句。 然后,您不必立即捕获已检查的方法。 这样,您可以稍后捕获exceptions (可能与其他exceptions )。

代码如下:

public void someMethode() throws SomeCheckedException {

    //  code

}

如果您不想在该方法中处理它们,那么稍后您可以处理exceptions

要捕获所有异常,可能会抛出一些代码块:(这也会捕获您自己编写的Exceptions

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

有效的原因是因为Exception是所有异常的基类。 因此,可能抛出的任何异常都是Exception (大写'E')。

如果要处理自己的异常,首先只需在通用异常之前添加一个catch块。

try{    
}catch(MyOwnException me){
}catch(Exception e){
}

虽然我同意捕获原始异常并不是一种好的方式,但是有一些方法可以处理异常,这些异常提供了卓越的日志记录以及处理意外情况的能力。 由于您处于异常状态,因此您可能对获取良好信息比对响应时间更感兴趣,因此性能的实例不应该是一个大问题。

try{
    // IO code
} catch (Exception e){
    if(e instanceof IOException){
        // handle this exception type
    } else if (e instanceof AnotherExceptionType){
        //handle this one
    } else {
        // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
        throw e;
    }
}

但是,这并没有考虑到IO也可以抛出错误的事实。 错误不是例外。 错误是与异常不同的继承层次结构,尽管它们共享基类Throwable。 由于IO可以抛出错误,你可能想要抓住Throwable

try{
    // IO code
} catch (Throwable t){
    if(t instanceof Exception){
        if(t instanceof IOException){
            // handle this exception type
        } else if (t instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else if (t instanceof Error){
        if(t instanceof IOError){
            // handle this Error
        } else if (t instanceof AnotherError){
            //handle different Error
        } else {
            // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
        }
    } else {
        // This should never be reached, unless you have subclassed Throwable for your own purposes.
        throw t;
    }
}

捕获基本异常'Exception'

   try { 
         //some code
   } catch (Exception e) {
        //catches exception and all subclasses 
   }

捕获异常是不好的做法 - 它太宽泛了,你可能会在自己的代码中错过像NullPointerException这样的东西。

对于大多数文件操作, IOException是根异常。 相反,更好地抓住它。

就在这里。

try
{
    //Read/write file
}catch(Exception ex)
{
    //catches all exceptions extended from Exception (which is everything)
}

您可以在单个catch块中捕获多个异常。

try{
  // somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
  // handle exception.
} 

你的意思是捕获一个Exception被抛出任何类型的,而不仅仅是特定的异常?

如果是这样:

try {
   //...file IO...
} catch(Exception e) {
   //...do stuff with e, such as check its type or log it...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM