java 抛出检查异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6302015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:16:30  来源:igfitidea点击:

Throw checked exceptions

javaexceptionexception-handlingchecked-exceptions

提问by Carven

A few of my methods in Java throw exceptions such as NoSuchElementException, IllegalArgumentException, etc. But when using these methods, these exceptions appear to be unchecked. In other words, caller of my methods is not required to do a try/catch on my methods that throw those exceptions. I read around it seems that Exceptions by default are "checked" and only Errors are the ones "unchecked". But somehow, the exceptions I throw are also unchecked. It is weird.

我在 Java 中的一些方法会抛出异常,例如 NoSuchElementException、IllegalArgumentException 等。但是在使用这些方法时,这些异常似乎是未经检查的。换句话说,我的方法的调用者不需要对抛出这些异常的方法进行 try/catch。我四处阅读似乎默认情况下异常是“已检查”的,只有错误是“未检查”的。但不知何故,我抛出的异常也是未经检查的。真奇怪。

How can I ensure that when my method throws an exception, the caller MUST catch the exception at compile time? Simply said, how can I throw a checked exception?

如何确保当我的方法抛出异常时,调用者必须在编译时捕获异常?简单的说,如何抛出受检异常?

Thanks!

谢谢!

回答by cHao

Only RuntimeExceptionand its subclasses are unchecked. (Well, Errorand its subclasses are as well, but you shouldn't be messing with Errors.) All you need to do to throw a checked exception is ensure that it doesn't extend RuntimeException.

OnlyRuntimeException及其子类未选中。(好吧,Error它的子类也是如此,但您不应该弄乱Errors。)抛出已检查异常所需要做的就是确保它不会扩展RuntimeException.

回答by Peter Lawrey

All sub-classes of Throwable are checked except sub-classes of Error and RuntimeException. (You can sub-class Throwable directly)

除了 Error 和 RuntimeException 的子类之外,Throwable 的所有子类都被检查。(你可以直接子类 Throwable )

The compiler checks these Exception, however they have no special place at runtime. i.e. you can throw a checked Exception without the compiler knowing and it will behave normally.

编译器检查这些异常,但是它们在运行时没有特殊的地方。即你可以在编译器不知道的情况下抛出一个检查过的异常,它会正常运行。

e.g.

例如

public static void throwChecked(Throwable t) /* no throws clause */ {
    Thread.currentThread().stop(t);
}

public static void main(String... args) /* no throws clause */ {
    throwChecked(new Throwable());
}

This compiles and prints the Throwable as you might expect.

这会按照您的预期编译并打印 Throwable。

回答by pevik

See this hack, it might help (hope it's not OT).

看到这个hack,它可能会有所帮助(希望它不是 OT)。

public class Test {

    // No throws clause here
    public static void main(String[] args) {
        doThrow(new SQLException());
    }

    static void doThrow(Exception e) {
        Test.<RuntimeException> doThrow0(e);
    }

    @SuppressWarnings("unchecked")
    static <E extends Exception> void doThrow0(Exception e) throws E {
        throw (E) e;
    }
}

回答by MeBigFatGuy

Whether an exception is checked or not checked is NOThow you throw it or declare it, it is only dependent on whether the exception you choose is derived from RuntimeException or not. The ones you list above, all are derived from RuntimeException and so clients of your method do not need to catch them.

一个例外是处于选中还是未选中是不是你如何把它或把它声明,这只是取决于你是否选择异常自RuntimeException或没有的。您上面列出的那些都是从 RuntimeException 派生的,因此您的方法的客户端不需要捕获它们。

回答by Gyan aka Gary Buyn

I think you should take a step back and learn the theory behind whyto throw a checked exception vs an unchecked exception. The Java tutorialon exceptions is a good resource.

我认为您应该退后一步,了解为什么要抛出受检查的异常与未经检查的异常背后的理论。关于异常的Java 教程是一个很好的资源。

From the page entitled Unchecked Exceptions — The Controversy:

从标题为Unchecked Exceptions - The Controversy的页面:

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.

运行时异常表示由编程问题导致的问题,因此,不能合理地期望 API 客户端代码从它们中恢复或以任何方式处理它们。

回答by amit

Exceptions that extends RuntimeExceptiondo not have to be declared.

扩展的异常RuntimeException不必声明。

You can declare the method: throws Exceptionor even throws Throwableand that will have to be handled (though it is not advised).

您可以声明方法:throws Exception或者甚至throws Throwable并且必须处理(尽管不建议这样做)。