0

Apologies if this has been discussed on other threads but I find it helps clarify my thinking when I am forced to write down my questions. I am trying to properly understand the concept of checked vs unchecked exceptions and exception translation in Java but I am getting confused. So far I understood that checked exceptions are exceptions that need to be always caught in a try/catch block otherwise I get a compile time error. This is to force programmers to think about abnormal situations that might happen at run time (like disk full etc). Is this right? What I did not get was why we have unchecked exceptions, when are they useful? Is it only during development time to debug code that might access an illegal array index etc? This confusion is because I see that Error exceptions are also unchecked as is RunTimeException but its not clear to me why they are both lumped together into an unchecked category?

EDIT: Ok, I think I can boil down my question to be more specific after thinking about it more. If a Java method throws a checked exception and it makes more sense to handle it two layers above, should I just keep rethrowing the same checked exception in every layer (i.e bubbling up) till it gets to the layer where it can be handled? Or alternatively I can throw a more specific (unchecked perhaps) exception that the layer above me can interpret more meaningfully?

user2399453
  • 2,930
  • 5
  • 33
  • 60

1 Answers1

0

During development you should work to eliminate the situations that would cause the majority of unchecked exceptions. Null pointers, array indices out of bounds, etc. Those are all problems that can be avoided with proper checks/development techniques in your code.

Being unable to read a file, open a network socket, or other things beyond the control of the application are thrown as checked exceptions, you need to handle those no matter how well your application is written.

Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • Thanks, so if I catch a checked exception and rethrow an unchecked one from the catch block, is the layer above me forced to catch the exception I just threw? – user2399453 Aug 23 '14 at 04:50
  • To me, handling run time exceptions in code is a bad programming practice. It should have been handled in your code by having checks or development techniques as Nick said above. – Loganathan Mohanraj Aug 23 '14 at 04:57
  • Thanks but not what I asked in the comment. The answer should be yes or no. – user2399453 Aug 23 '14 at 04:59
  • Nope, the exception is now unchecked so it'll rip right through. – Nick Veys Aug 23 '14 at 17:58