Search code examples
javamulti-catch

WebApplicationException and NotFoundException in multi-catch


So my question is this :

Basically I've a method with a try-catch block where I'm catching a WebApplicationException (javax.ws.rs.WebApplicationException) but my method is throwing NotFoundException (com.sun.jersey.api.NotFoundException) .

so I wanted to handle both like this :

try {


} catch (WebApplicationException e | NotFoundException e) {


}

However I get the following compile-time error :

The exception NotFoundException is already caught by the alternative WebApplicationException

But why is that? NotFoundException is supposed to come from a totally different package (jersey), isn't it ?

Also - it works fine if i put them in separate catch() blocks.

Please help.


Solution

  • You can try the child exception first like.

    try {
    
    } catch (NotFoundException e) {
    } catch (WebApplicationException e) {
    }
    

    But why is that? NotFoundException is supposed to come from a totally different package (jersey)

    If you go through the jersey's NotFoundException source code than you found, NotFoundException extends WebApplicationException. Here, NotFoundException inherit the javax.ws.rs.WebApplicationException class. So, WebApplicationException is a parent class of com.sun.jersey.api.NotFoundException, that's why you get an error.

    package com.sun.jersey.api;
    
    import java.net.URI;
    import javax.ws.rs.WebApplicationException;
    
    /**
     * A HTTP 404 (Not Found) exception.
     * 
     * @author [email protected]
     */
    public class NotFoundException extends WebApplicationException