Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare unchecked exceptions in the throws specification?

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?

like image 442
mafu Avatar asked Jan 01 '14 18:01

mafu


People also ask

Can we declare unchecked exception in throws?

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.

Can we throws unchecked exception in Java?

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.

Is it good practice to catch unchecked exceptions?

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.

For which type of exception the throws clause is mandatory?

The throws clause must be used with checked exceptions.


1 Answers

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.

like image 143
Sergey Kalinichenko Avatar answered Oct 02 '22 10:10

Sergey Kalinichenko