Why it is not recommended to handle unchecked exceptions by using try...catch blocks? Why we need to avoid them through some conditional checkings only?
-
I'm not sure what you mean, but generally speaking - exception handling is most 'costly' than doing a condition check and often an easier to read control flow; so it might be that aspect you're referring to? – Allan S. Hansen Aug 23 '14 at 16:34
-
@AllanS.Hansen Thank you for your response. But we are handling checked exceptions through try..catch blocks only and it is recommend. But i'm unable understand y it is not recommend in case of unchecked exceptions. – user3971066 Aug 23 '14 at 16:42
-
The theory is that unchecked exceptions are (assumed to be) "fatal", and cannot generally be tolerated in a way that assures that the program will continue to execute correctly. That's the theory. – Hot Licks Aug 23 '14 at 19:18
1 Answers
A fundamental limitation of Java's exception model is that if a method throws an exception it's generally not possible for its caller to know the circumstances surrounding it. If code which is about to compute x % y
tests whether y
is zero, it can know the precise circumstances under which a DivideByZeroException
would have occurred, and handle the situation appropriately. If the condition is instead handled by catching the exception, the programmer may expect that the exception will have resulted from trying to compute x % y
when y
is zero, but would also catch divide-by-zero exceptions that occur for unexpected reasons (e.g. calling a method which is supposed to partition a set, but has a bug that causes it to try to subdivide the set into zero pieces). There's no way when catching an exception to specify that one only wants the exception to be caught if it was thrown for the expected reasons. In practice, both checked and unchecked exceptions have this same problem, but it's more common for unchecked exceptions to get thrown in unexpected circumstances.

- 77,689
- 9
- 166
- 211