Exception Handling
Exception Handling
Exception Handling
Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time.
In other words, an exception is a run-time error. For example, the user enters an invalid input,
the program attempts to open a file that doesn’t exist, the network connection hangs up or the
program attempts to access an out-of-bound array element. When these runtime errors come
into the picture, JAVA EXCEPTIONS plays a very important role. When such an error within a
JAVA method occurs, the method creates an exception object and hands it off to the runtime
system. The exception object contains information about the exception, including its type and
the state of the program when the error occurred. The runtime system is then responsible for
finding some code to handle the error. In JAVA terminology, creating an exception object and
handling it to the runtime system is called throwing an Exception.
After a method throws an exception, the runtime system leaps into action to find
someone to handle the exception. The set of possible “someone” to handle the exception is
the set of method in the call stack of the method where the error occurred. The runtime
system searches backwards through the call stack. Beginning with the method in which the
error occurred, until it finds a method that contains appropriate if the type of the exception
thrown is the same as the type of the exception handled by the handler. Thus, the exception
bubbles up through the call stack until an appropriate handler is found and one of the calling
methods handles the exception. The exception handler chosen is said to catch the
Exception.
If the runtime system exhaustively searches all of the methods on the call stack without
finding an appropriate exception handler, the java program terminates.
Java Exception handling is managed by five keywords try, catch, throw, throws and
finally. This is way how they work
Program statements that you want to monitor for exceptions are contained within a try
block.
If an exception occurs with the try block, it is thrown.
Your code can catch this exception using catch and handle it in some rational manner.
System generated exceptions are automatically thrown by the java runtime system. To
manually throw an exception use the keyword throw.
An exception that is thrown out of a method must be specified as such by a throws clause
Any code that absolutely must be executed before a method returns is put in a finally
block.
1
Exception Handling
Exception Types
Throwable
Exception Error
All Exception types are subclasses of the built in class Throwable. Thus Throwable is at the
top of the exception class hierarchy. Immediately below Throwable are two subclasses one is
headed by Exception and the other is Error. There is an important subclass of Exception
called as RuntimeException. Exceptions of the type Error are used by the Java run-time
system to indicate errors having to do with the runtime environment, itself. Stack overflow is
one of the example of such an error.
Although the default exception handler provided by the Java runtime System is useful
for debugging, you will usually want to handle an exception yourself. Doing so provides two
benefits : First it allows you to fix the error. Second it prevents the program from automatically
terminating.
e.g
class div
{
public static void main(String args[])
{
int d,a;
try
{
d=0;
a = 100/d;
System.out.println(“Will this print”);
}catch(ArithmeticExpression e)
{
// Catch divide by zero error
System.out.println(“Divide by Zero Error”);
}
System.out.println(“After catch statement”);
}
}
2
Exception Handling
Sample program : It creates and throws an exception. The handler catches the exception
rethrows it to the outer handler.
// Demonstrate throw
class ThrowDemo
{
static void demoprac()
{
try
{
throw new NullPointerException(“demo”);
3
Exception Handling
}
catch(NullPointerException e)
{
System.out.println(“Caught Inside demoprac”);
throw e;
}
}
public static void main(String args[])
{
try
{
demoprac();
}
catch(NullPointerException e)
{
System.out.println(“Recaught : “+e);
}
}
}
// Example of a throw
class ThrowsDemo
{
static void throwone( ) throws IllegalAccessException
{
System.out.println(“Inside throwone”);
throw new IllegalAccessException(“demo”);
}
4
Exception Handling
{
throwone();
}
catch(IllegalAccessException e)
{
System.out.println(“Caught : “+e);
}
}
}
try
{
statements ;
}
catch(TheException e)
{
handling e ;
}
finally
{
finalstatements ;
}
The code in the finally block is executed under all circumstances, regardless of whether an
exception occurs in the try block and whether it is caught. Consider three possible cases.
If no exception arises in the try block, finalstatements is executed and the next statement
after the try/catch block is executed
If one of the statement causes an exception in the try block that is caught in a catch
clause, the rest of the statements in the try block are skipped, the catch clause is
executed. If the catch clause does not rethrow an exception, the next statement after the
try/catch block is executed. If it does the exception is passed to the caller of this method.
If one of the statement causes an exception that is not caught in any catch clause, the rest
of the statements in the try block are skipped, the finally clause is executed and the
exception is passed to the caller of this method.
5
Exception Handling
because compiler does not check to see if a method handles or throws these exceptions. For
checked exceptions one has to throw the exception.
Exception Meaning
ArithmeticException Arithmetic error such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreException Assignment to an array element of an incompatible type
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method
IllegalMonitorStateExceptionq Illegal monitor operation such as waiting on an unlocked
thread
IllegalStateException Environment or application is in incorrect state
IllegalThreadStateException Requested operation not compatible with current thread
state
IndexOutOfBoundsException Some type of index is out of bounds
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of Null reference
NumberFormatException Invalid conversion of string to a numeric format.
StringIndexOutOfBounds Attempt to index outside the bounds of a string
UnSupportedOperationException An unsupported operation was encountered
6
Exception Handling
MyException(int a)
{
detail = a;
}
public String toString( )
{
return “MyException [“ + detail + ”]”
}
}
class Example
{
static void computer(int a) throws MyException
{
System.out.println(“Called compute (“+a”)”;
if (a > 10)
throw new MyException(a);
System.out.prinln(“Normal Exit”);
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch(MyException e)
{
System.out.println(“Caught”+e);
}
}
}
Questions
1. Describe Java Throwable class hierarchy and the type of exceptions
2. How do you throw an exception
3. How do you catch an exception