如何在java中再次抛出IOException?

use*_*818 1 java methods exception ioexception throw

码:

 catch (IOException e) {
        LOGGER.error("IOException exception happened");
        //now need throw again the same exception to be 
                       //catched in    the    upper method
    }
Run Code Online (Sandbox Code Playgroud)

但当我尝试简单:

  catch (IOException e) {
        LOGGER.error("IOException exception happened");
        //now need throw again the same exception to be 
                       //catched in    the    upper method
               throw e;
    }
Run Code Online (Sandbox Code Playgroud)

Eclipse假设我把"throw e"放在try catch块中.但这是无稽之谈.怎么解决这个问题?谢谢.

Pau*_*ora 7

由于IOException是一个经过检查的异常,IOException如果您希望它传播,则该方法需要声明为throw .例如:

void myMethod() throws IOException {
    try {
        //code
    }
    catch(IOException e) {
        LOGGER.error("IOException exception happened");
        throw e;
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*ski 5

第二个代码片段就好了.请记住,您必须将您的方法声明为:

public void myMethod() throws IOException {
    ...
}
Run Code Online (Sandbox Code Playgroud)