Java – “Unhandled exception” though it’s actually handled

Even though you’re throwing in after checking instanceof, that’s a runtime check, and e is still declared as Exception. While the compiler could infer from this that that line will only ever throw instances of IllegalArgumentException, that’s not something it currently does (I guess it might with instanceof pattern matching in the future).

So, change

if (e instanceof IllegalArgumentException) {
    throw e; //Javac complains in this 
}

to

if (e instanceof IllegalArgumentException) {
    throw (IllegalArgumentException) e;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top