Wednesday, February 16, 2011

Checked vs unchecked exceptions vs Error

Checked exceptions

Checked exceptions are subclasses of Exception .

Checked exceptions are the objects of the Exception class or any of its subclasses excluding the Runtime Exception class. Checked Exceptions are the invalid conditions that occur in a java program due to invalid user input, network connectivity problem or database problems.

Java uses the try-catch block to handle the checked exceptions. The statements within a program that throw an exception are placed in the try block. You associate an exception-handler with the try block by providing one or more catch handlers immediately after the try block.

Various checked exceptions defined in the java.lang.package are,

  1. ClassNotFoundException
  2. IllegalAccessException
  3. InstantiationException
  4. NoSuchMethodException

Unchecked exceptions

It represent defects in the program (bugs), that effect due to programming error. It often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."

These are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException .

Various Unchecked Exceptions are,

  1. ArithmeticException
  2. ArrayIndexOutOfBoundsException
  3. ArrayStoreException
  4. ClassCastException
  5. IllegalArgumentException
  6. NegativeArraySizeException
  7. NullPointerException
  8. NumberFormatException

Error

The errors in java are external to the application. These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement. Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.IOError would be thrown. This error will cause the program to terminate but if an application wants then the error might be caught. An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions.

No comments:

Post a Comment

Chitika