How to throw again IOException in java? [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-24 06:46:04

问题


Code:

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

But when I try simply:

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

Eclipse supposes to me put "throw e" in try catch block. But this is nonsense. How fix this problem? Thanks.


回答1:


Since IOException is a checked exception, that method needs to be declared as throwing IOException if you want it to propagate. For example:

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



回答2:


The second code fragment is just fine. Just remember that You have to declare Your method as:

public void myMethod() throws IOException {
    ...
}



回答3:


Try adding throws IOException to your method, e.g.:

private void yourMethodName() throws IOException {
    # your method
}

Then Eclipse won't ask for the second try catch block.



来源:https://stackoverflow.com/questions/11209885/how-to-throw-again-ioexception-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!