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!
Exceptions that extends
RuntimeException
do not have to be declared.You can declare the method:
throws Exception
or eventhrows Throwable
and that will have to be handled (though it is not advised).See this hack, it might help (hope it's not OT).
Whether an exception is checked or not checked is NOT how 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.
Only
RuntimeException
and its subclasses are unchecked. (Well,Error
and its subclasses are as well, but you shouldn't be messing withError
s.) All you need to do to throw a checked exception is ensure that it doesn't extendRuntimeException
.All sub-classes of Throwable are checked except sub-classes of Error and RuntimeException. (You can sub-class Throwable directly)
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.
This compiles and prints the Throwable as you might expect.
I think you should take a step back and learn the theory behind why to throw a checked exception vs an unchecked exception. The Java tutorial on exceptions is a good resource.
From the page entitled Unchecked Exceptions — The Controversy: