[go: up one dir, main page]

0% found this document useful (0 votes)
2 views7 pages

Exception Handling

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 7

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.

This is the general form of an exception handling block


Try
{
// Block of code to monitor the error
}
catch(ExceptionType1 exObject)
{
Exception Handler for exceptiontype1
}
catch(ExceptionType2exObject)
{

1
Exception Handling

Exception Handler for exceptiontype2


}
// . . . . . . .
finally
{
//Block of code to be executed before try block ends
}

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

Multiple catch clause


class div
{
public static void main(String args[])
{
int a = args.length;
try
{
int b = 42/a;
int c[] = {1};
c[40] = 99;
}catch(ArithmeticExpression e)
{
// Catch divide by zero error
System.out.println(“Divide by Zero Error”);
} catch(ArrayIndexOutOfBoundsException e)
{
// Catch divide by zero error
System.out.println(“Array Index out of Bounds Exception”);
}
System.out.println(“After try/catch Block”);
}
}

The throw Clause


It is possible to throw an exception explicitly using the throw statement. The general form of
the statement is shown below
Throw Throwableinstance ;
Here Throwableinstance must be an object of the type Throwable or a subclass of
Throwable. The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed. The nearest enclosing try block is inspected to see
if it has a catch statement that matches the type of the exception. If it does find a match,
control is transferred to that statement. If not, then the next enclosing try statement is
inspected and so on. If no matching catch is found, then the default exception handler halts
the program and prints the stack trace.

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);
}
}
}

The throws Clause


If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of that method can guard themselves against that exception. You
do this by including a throws clause in the methods declaration.A throws clause lists the type
of exceptions that a method might throw. This is necessary for all exceptions, except those for
the type Error or RuntimeException or any of their subclasses. All other exceptions that a
method can throw must be declared in the throws clause. If they are not, a compile-time error
will result.
The general syntax is
Type method-name(parameter list) throws exception-list
{
// Body of the method
}
Here exception-list is a comma-separated list of the exceptions that a method can throw.

// Example of a throw
class ThrowsDemo
{
static void throwone( ) throws IllegalAccessException
{
System.out.println(“Inside throwone”);
throw new IllegalAccessException(“demo”);
}

public static void main(String args[])


{
try

4
Exception Handling

{
throwone();
}
catch(IllegalAccessException e)
{
System.out.println(“Caught : “+e);
}
}
}

The finally Clause


Occasionally, you may want some code to be executed regardless of whether the
exception occurs and whether it is caught. Java has finally clause that one can use to
accomplish this objective. The syntax is as follows

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.

Java’s Built in Exceptions


Inside the standard java.lang java defines several exception classes. The most general
of these exceptions are subclasses of the standard type RuntimeException. Since java.lang
is implicitly imported into all java programs, most exceptions derived from RuntimeException
are automatically available. In java terminology these are called as unchecked exceptions

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

Cautions when using Exceptions


Exception handling separates error-handling code from normal programming tasks, thus
making program easier to read and to modify. However one has to be aware that exception
handling usually requires more time and resources because it requires instantiating a new
exception object, rolling back the call stack and propagating the errors to the calling method.

Creating your own Exception Subclasses


The following example declares a new subclass of Exception and then uses that subclass to
signal an error condition in a method. It overriders the toString( ) method, allowing the
description of the exception to be displayed using prinln( ).
// This program creates a custom exception type
class MyException extends Exception
{
private int detail;

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

You might also like