Thursday, 14 March 2013

Checked vs Unchecked Exceptions

Leave a Comment

Checked Exceptions Vs Unchecked Exceptions in Java

At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.
The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.
Now let us see a see small discussion on why exceptions are classified as checked exceptions and unchecked exceptions.
Those unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking in java because they can occur at many points in the program and recovery from them is difficult or impossible.

Example: OutOfMemoryError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java, having to declare such exceptions would not aid significantly in establishing the correctness of programs.

Example: NullPointerException

Thrown when an application attempts to use null in a case where an object is required.
So the java compiler doesn’t forces them to be declared in the above two cases.

Synchronous and Asynchronous Exceptions in Java

The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception.
An asynchronous exception in java can occur at any point in the execution of a program.
They occur only as a result of:
  1. An invocation of the stop methods of class Thread or ThreadGroup
  2. An internal error in the Java virtual machine


Post a Comment