本文介绍了如何在java中识别已检查和未检查的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读异常时,我总会遇到已检查的异常和未经检查的异常,所以想知道如何区分这是什么?

While reading about exception, I will always come across checked exceptions and unchecked exceptions, So wanted to know how to distinguish that which is what?

编辑:我想要要知道我是否创建了任何异常类,那么我如何创建一个被检查的或未经检查的?

I want to know if i create any exception class then how can i create as a checked or as an unchecked?

每个的重要性是什么?

推荐答案

所有 Throwable s除了 java.lang.RuntimeException 或 java.lang.Error 。正确地说,在Java中,exception是 java.lang.Exception 的子类,errors是 java.lang.Error java.lang.Throwable 通常不直接进行子类化。

All Throwables except subclasses of java.lang.RuntimeException or java.lang.Error are checked. Properly, in Java, "exceptions" are subclasses of java.lang.Exception, "errors" are subclasses of java.lang.Error and java.lang.Throwable is not usually subclassed directly.

程序不应该创建自己的错误子类(虽然文档相当模糊)所以一般如果你不想检查它,你总是使用 RuntimeException 创建例外

Programs are not supposed to create their own Error subclasses (though the documentation is rather ambiguous on that) so generally you always create Exceptions, using a RuntimeException if you don't want it to be checked.

要知道在运行时是否有选中例外,您可以使用:

To know at run-time if you have a checked exception you could use:

if(throwable instanceof Exception && !(throwable instanceof RuntimeException)) {
    // this is a checked Exception
    }

已检查的异常是必须在catch子句中处理或声明为在方法签名中抛出的异常;编译器强制执行此操作。通常,对于应由调用代码处理的异常使用已检查的异常,而未经检查的异常用于由编程错误导致的条件,并应通过更正代码来修复。

A checked exception is one which must be either handled in a catch clause, or declared as being thrown in the method signature; the compiler enforces this. Generally, one uses checked exceptions for exceptions which should be handled by the calling code, while unchecked exceptions are for conditions which are the result of a programming error and should be fixed by correcting the code.

这就是说Java社区中存在很多关于使用已检查异常与未经检查的异常的效果的争论 - 这是在这个答案中深入讨论的主题方式。

That said there is much debate in the Java community about the efficacy of using checked exceptions vs. unchecked exceptions everywhere - a subject way to deep to discuss in this answer.

编辑2012-10-23:在回复评论(非常有效)时,为了澄清,以下将是确定是否需要捕获的可投掷的是经过检查的 Throwable ,而非选中的 例外

EDIT 2012-10-23: In response to comments (which are quite valid), to clarify, the following would be what is required to determine if a captured Throwable is a checked Throwable as opposed to a checked Exception:

if(obj instanceof Throwable && !(obj instanceof RuntimeException) && !(obj instanceof Error)) {
    // this is a checked Throwable - i.e. Throwable, but not RuntimeException or Error
    }

如果有问题的对象已知成为 Throwable 的实例(例如它被抓住了,只需要上面'if'的第二部分(例如测试Throwable是多余的)。

If the object in question is known to be an instance of Throwable (e.g. it was caught), only the second part of the above 'if' is needed (e.g. testing for Throwable is redundant).

这篇关于如何在java中识别已检查和未检查的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:42
查看更多