Pradeep's Blog

Google

Monday, March 20, 2006

Good Ways of Handling Exception in Java

Not that I know everything in exception handling, but here's what i think are good ways of handling exceptions.
  • Never use a catch block that suppresses the exception (for example by doing nothing). This makes the program to continue on as if nothing ever happened.
  • Always try to catch the specific exception, unless you are sure that it makes no difference. For example when invoking a method that throws more that one type of exception, never just catch them using Exception.
  • Handle exceptions where actions can be taken to deal with the exceptions caused. For example if a block of code throws an exception, handle it there only ifs possible for you to recover from the exception, or else throw the exception to a level where the system can recover.
  • Having said to throw the exceptions to an upper level where it can be comfortably handled, it dosent mean that you throw an fileNotFound Exception to a place where the applications logical level.
  • When deciding on checked or unchecked exceptions exceptions for your APIs, its good to throw an checked exception if its possible for the client to recover from the exception, or else it can be should unchecked exception.
  • Allways clean up afer exception using finally.

0 Comments:

Post a Comment

<< Home