简体   繁体   English

在 Stream 中抛出 Throwable -> “未处理的异常类型 Throwable”

[英]throw Throwable in Stream -> "Unhandled exception type Throwable"

Does anyone know why throwing a Throwable or an Exception in a Stream doesn't compile in the code below?有谁知道为什么在 Stream 中抛出 Throwable 或 Exception 不能在下面的代码中编译?

Environment: Win 10 x64, Eclipse 2020-03, openJDK v14环境:Win 10 x64,Eclipse 2020-03,openJDK v14

public void myMethod(final boolean myBoolean) throws Throwable {

    if (myBoolean) {throw new Exception("Compiler accepts this OK");}
    if (myBoolean) {throw new Throwable("Compiler accepts this OK");}

    Stream.of("").forEach(s -> {throw new Error("");});

    Stream.of("").forEach(s -> {throw new RuntimeException("");});

    Stream.of("").forEach(s -> {throw new Exception("Compiler -> Unhandled exception type Exception");});

    Stream.of("").forEach(s -> {throw new Throwable("Compiler -> Unhandled exception type Throwable");});
}

I've declared that the Method throws Throwable & outside the Stream it compiles ok, but inside, it seems I can only throw subclasses of Error & RuntimeException.我已经声明该方法在它编译好的 Stream 之外抛出 Throwable &,但在内部,我似乎只能抛出 Error & RuntimeException 的子类。

Short answer is that Exception and Throwable are checked exceptions.简短的回答是ExceptionThrowable是检查异常。 The rules for checked exceptions say that they must either be caught within the method (or lambda) in which they are thrown, or they must be declared in the throws list of the method (or functional interface).已检查异常的规则规定,它们必须要么在抛出它们的方法(或 lambda)中被捕获,要么必须在方法(或功能接口)的throws列表中声明。

(See also: What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it? for some background.) (另请参阅: “错误:未报告的异常 <XXX>; 必须被捕获或声明为被抛出”是什么意思,我该如何解决?对于某些背景。)

Neither of those things is practical in your example.在您的示例中,这些事情都不实用。 So you should avoid throwing checked exceptions in that context.因此,您应该避免在该上下文中抛出已检查的异常。 Use unchecked exceptions instead;改用未经检查的异常; ie RuntimeException or subclasses.RuntimeException或子类。


Note that it is a bad idea to declare a method as throws Throwable or throws Exception .请注意,将方法声明为throws Throwablethrows Exception是一个坏主意。 This effectively forces the caller to deal with 1 exceptions that it (typically) has no knowledge of.这有效地迫使调用者处理它(通常)不知道的1 个异常。 If you want to use checked exceptions, use ones that are specific to the "exceptional condition" you are signalling.如果要使用已检查异常,请使用特定于您发出信号的“异常条件”的异常。 Declare a custom exception if necessary.如有必要,声明一个自定义异常。

1 - ... either by handling them, or declaring them in its method signature! 1 - ...要么处理它们,要么在方法签名中声明它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM