Thursday, September 07, 2006

Java Exceptions Best Practices

Java provides an efficient way to handle unexpected conditions that can occur in the program. When there is an error or bug in the program then the program terminates as soon as an error is encountered leaving the program in an in consistent state, to avoid this Java makes use of Exception Handling mechanism to a great advantage so that when ever there is an exceptional condition then the program handles it gracefully and continues program execution.

The whole concept of exceptions/errors is handled by the java.lang.Throwable class. It has two subclasses - Error and Exception. We generally need not handle Errors, they are handled by JVM. Example of Error is OutOfMemoryError.

Exceptions are of two types -Checked exceptions and Unchecked exceptions.

Checked exceptions should either be declared in the throws clause or caught  in the catch block. Unchecked exceptions need not be declared in the throws clause but can to be caught in the catch clause.

Optimization techniques in Exceptions

  • In a catch block avoid using the generic class Exception. For each try block use specific catch blocks based on what can go wrong in your code.
  • Do not use Exception handling for anything other than exception handling like to control the flow of your program.
  • Whenever you are using a throws clause always use the specific subclass of Exception like FileNotFoundException rather than using throws Exception.
  • Use exception handling generously-Very little overhead is imposed by using exception handling mechanism unless an exception occurs. But when an exception occurs it imposes an overhead in terms of execution time.
  • Always use the finally block to release the resources like a database connection, closing a file or socket connection etc. This  prevents resource leaks even if an exception occurs.
  • When using method calls always handle the exceptions in the method where they occur, do not allow them to propagate to the calling method unless it is specifically required. It is efficient to handle them locally since allowing them to propagate to the calling method takes more execution time.
  • Do not use Exception handling in loops. It is better to place loops inside try/catch blocks than vice versa. Here is an code snippet that gives bench mark.

Key Points

  1. Be specific while handling the exception in your catch block.
  2. Do not use Exception Handling to control programming flow.

Get more information

Tags: java exceptions, handle exceptions, try block, method calls, finally block

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Comments on "Java Exceptions Best Practices"