抛出检查异常 [英] Throw checked exceptions
问题描述
我用Java编写的一些方法抛出异常,例如NoSuchElementException,IllegalArgumentException等.但是,当使用这些方法时,这些异常似乎未被检查.换句话说,不需要我的方法的调用者对抛出这些异常的方法进行尝试/捕获.我阅读了一下,似乎默认情况下异常是选中的",而只有错误是未选中的".但是以某种方式,我抛出的异常也未被检查.很奇怪.
如何确保当我的方法引发异常时,调用方必须在编译时捕获该异常?简而言之,我该如何抛出一个检查异常?
谢谢!
仅未选中RuntimeException
及其子类. (好吧,Error
及其子类也一样,但是您不应该弄混Error
s.)抛出受检查的异常所需要做的就是确保它不会扩展RuntimeException
. /p>
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.
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!
Only RuntimeException
and its subclasses are unchecked. (Well, Error
and its subclasses are as well, but you shouldn't be messing with Error
s.) All you need to do to throw a checked exception is ensure that it doesn't extend RuntimeException
.
这篇关于抛出检查异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!