包括抛出异常的方法签名?

Method signature including the throws exception?

我知道方法签名包括方法名称及其参数列表

但是throws Exception呢?

public List<ServiceStatusVo> listServiceStatuses() throws RetrieverException {
    ...
    return list;
}

如果它不包括那么为什么我不能传递以下lambda:

() -> listServiceStatuses()

但我可以通过

() -> {
    try {
        return listServiceStatuses();
    } catch (RetrieverException e) {
    }
}

我也可以再扔

() -> {
    try {
        return listServiceStatuses();
    } catch (RetrieverException e) {
        throw e;
    }
}

我知道 Supplier<T> 功能接口,这让我很困惑 if throws 不属于 方法签名

感谢您的帮助。

这不是直接关于方法签名的。来自 JLS Sec 11.2.3:

It is a compile-time error if a lambda body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the function type targeted by the lambda expression.

这有点令人惊讶 - 我必须承认我最初的想法是异常 方法签名的一部分。

但请记住,"checked exception" 意味着 compile-time checked exception: the compiler makes sure that you have handled all checked exceptions; but once it has been compiled, checked and unchecked exception types are treated just the same. Notice that that the JVM spec 在异常部分甚至没有提到检查。

因此,正如在运行时所见,该方法可以抛出任何异常。正如语言规范中所述:

Two methods or constructors, M and N, have the same signature if they have the same name, the same type parameters (if any) (§8.4.4), and, after adapting the formal parameter types of N to the the type parameters of M, the same formal parameter types.