Search code examples
javaexceptionmethodsioexceptionthrow

How to throw again IOException in java?


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.


Solution

  • 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;
        }
    }