Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to throw an Exception to the method caller inside a try catch body?

When I have a method like this:

public static void foo(String param) throws IOException
{
    try
    {
         // some IOoperations
         if (param.isEmpty())
         {
              throw new IOException("param is empty");
         }
         // some other IOoperations

    } catch (Exception e) {
        /* handle some possible errors of of the IOoperations */
    }
}

And when the IOException ("param is empty") is thrown, it is catched by the try-catch in that body. But this exception is meant for the caller of this method. How can I do this properly? Is there something "pure-Java" to do this or do I have to create an other type of Exception which is not an instance of IOException to avoid the try-catch body will handle it?

I know you would suggest to use a IllegalArgumentException in this case. But this is a simplified example of my situation. In fact the Exception I throw is an IOException.

Thanks

like image 565
Martijn Courteaux Avatar asked Oct 01 '10 20:10

Martijn Courteaux


1 Answers

Making your own custom subclass of IOException might be a good idea. Not only to solve this problem, but sometimes it's a bit 'user-friendlier' for your API users.

Then you could ignore it in catch block (rethrow it immediately)

} catch (FooIOException e) {
    throw e;
} catch (Exception e) {
    /* handle some possible errors of of the IOoperations */
}
like image 184
Nikita Rybak Avatar answered Sep 17 '22 20:09

Nikita Rybak