I'm aware checked exceptions have to be handled or specified, but unchecked exceptions are optional.
If for some reason I can reasonably expect an unchecked exception to occur in a method, should I add it to the throws specification? Or should I keep the specification as short as possible?
Unchecked exceptions can be propagated in the call stack using the throw keyword in a method. Checked exceptions can be propagated using the throw keyword when the method that throws the exception declares it using the throws keyword.
Throwing unchecked exception from a checked exception Yes, we can catch compile time exception (checked) and in the catch block we can wrap it with in a run time exception (unchecked) and re-throw it.
but in case of unchecked exception compiler don't checks it when it compiles your code means you can leave it. Handling a Exceptions means you know about how and when that exceptional situation may arise so you handle them. instead of handling it.
The throws clause must be used with checked exceptions.
If for some reason I can reasonably expect an unchecked exception to occur in a method, should I add it to the throws specification?
Since unchecked exceptions indicate programming errors, declaring them in the throws
clause should be avoided. Generally, catching these exceptions should not be attempted, except for the highest level of your program. There are a few exceptions (pun intended) to this rule - for example, in production code you should be catching NumberFormatException
.
Note: Sometimes, authors of frameworks make their base exception inherit RuntimeException
(e.g. HibernateException
). Exceptions like that should be caught as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With