Java - "Unhandled exception" 虽然实际处理了

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

我有一个类似于下面的设置。在 AClass 中,Java 行 throws e 编译器抱怨 -

Unhandled exception: <path-to>.DatastoreException

(来自 jdoodle 的可编辑分享 - jdoodle.com/a/2xbl

这是为什么?如果异常是 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();
    }
}

即使您在检查 instanceof 之后投入使用,那也是运行时检查,并且 e 仍然声明为 Exception。虽然编译器 可以 从中推断出该行只会抛出 IllegalArgumentException 的实例,但这不是它当前所做的事情(我猜它可能与 instanceof 模式以后匹配)。

所以,改变

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

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