Search code examples
javaexceptionjavac

Java - "Unhandled exception" though it's actually handled


I have a setup similar to below. In AClass the Java compiler in line throws e complains -

Unhandled exception: <path-to>.DatastoreException

(Editable share from jdoodle - jdoodle.com/a/2xbl)

Why is that? Aren't I only throwing if the exception is an IllegalArgumentException?

import java.lang.IllegalArgumentException;
import <path-to>.DependencyException;
import <path-to>.DatastoreException;

public class AClass {
    public void someMethod() {
        try {
            new BClass().thisThrowsDatastoreException();
        } catch (Exception e) {
            if (e instanceof IllegalArgumentException) {
                throw e; //Javac complains in this line
            } else if (e instance of DatastoreException) {
                throw new DependencyException(e);
            }
        }
    }
}

public class BClass {

    public BClass() {}
    
    public void thisThrowsDatastoreException() throws DatastoreException {
        throw new DatastoreException();
    }
}

public class DatastoreException extends Exception {
    private static final long serialVersionUID = -2L;
    public DatastoreException() {
        super();
    }
}


public class DependencyException extends RuntimeException {
    private static final long serialVersionUID = -1L;
    public DependencyException() {
        super();
    }
}


Solution

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