Friday, 5 June 2015

Java Exception Handling

An exception/error is an abnormal condition that breaks/disrupts the normal program flow. The abnormal condition occurs at run-time i.e. during code execution.

For example, a C program gets terminated when division by zero is encountered at the run-time as this is not a defined operation and results in run-time error. The other familiar example in case of C-language is that of null pointer exception, which occurs when we try to access a memory location through an un-initialized pointer. The program gets terminated in this case also.

Java has a separate construct for exception/error handling like C++. It is possible to recover from an exception/error at run-time and continue the program execution using the exception-handling construct.

A Java exception/error is an object of class Exception/Error or one of its sub-classes. JVM creates an object of class Exception/Error or one of their sub-classes whenever exception/error occurs at the run-time. The exception/error object contains details about the exception/error, which can be accessed using the public methods provided for this purpose.

Traditional Approach of Exception/Error Handling:

Use of if(), goto and return codes for propagating error back to calling method.

Advantage of Exception/Error Handling

  • Error-handling code is separated from the normal program flow to increase the

    readability and maintainability.

    We can easily say where the exception/error will be handled. Exceptions/Errors
    propagate up the call stack at runtime- first up the enclosing try blocks and then back to the calling method- until an exception handler catches them.
     
  • The location of the exception/error is known exactly as entire stack trace is available to the user. This is very helpful in debugging.
     
  • Programmer gets a chance to recover from the error/abnormal condition.
     
  • With Java, it is not must to test if an exception/error condition happens. Adding more error/exception handlers simply requires adding more catch clauses, but the original program flow need not be touched.

When Exceptions/Errors can occur?

There are many cases where abnormal conditions occur during program execution, such as:

  • The class file you want to load may be missing or in the wrong format.
  • Integer division by zero.
  • Array index is not in the valid range (i.e. from 0 to length-1).
  • The file you are trying to open may not exist.
  • The String, which you want to convert to a number, is having invalid characters so that it cannot be converted to a number.
  • You want to create an object but no more memory is available.

No comments:

Post a Comment