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
.