如何在java中再次抛出IOException?

时间:2012-06-26 14:44:09

标签: java exception methods ioexception throw

代码:

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

但是当我尝试简单时:

  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假设我把“throw e”放在try catch块中。但这是无稽之谈。 怎么解决这个问题? 感谢。

3 个答案:

答案 0 :(得分:7)

由于IOExceptionchecked exception,如果您希望它传播,则需要将该方法声明为抛出IOException。例如:

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

答案 1 :(得分:5)

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

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

答案 2 :(得分:1)

尝试在您的方法中添加throws IOException,例如:

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

然后Eclipse不会要求第二次尝试catch块。