You are on page 1of 12

JAVA CORE

EXCEPTION HANDLING

By: Subramanian Date: 15 July 2008

EXCEPTION HANDLING

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred.
Creating an exception object and handing it to the runtime system is called throwing an exception.

The Three Kinds of Exceptions

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses. Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses. Errors and runtime exceptions are collectively known as unchecked exceptions.

Throw

You have only been catching exception that are thrown by the java run time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general forms of throw is shown here Throw throwableInstance;

1. The flow of execution tops immediately after the throw statement; any subsequent statement are not executed. 2. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. 3. 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. 4. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

Class throwdemo{
static vodi demoproc(){ try{

Example

throw new NullPointerException(Demo); }catch(NullPointerException e){ S.o.p(Caught inside demoproc.); throw e; } } p v s m(S args[]){ try{ demoproc(); }catch(NullPointerException e){ S.o.p(Recaught :+e); } } }

Throws
1. If a method is capable of causing an exception that is does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. 2. You do this by including a throws clause in the method, might throw, this is necessary for all exception, except those of type Error or Runtime Exception, or any of their sub classes. Type method-name(Parameter-list) throws exception list { //body of the method; } Example: public void writeList() throws IOException,ArrayIndexOutOfBoundsException { //Statement; }

Finally

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Creating Your Own Exception Subclasses

Although javas built-in exception handle most common errors, you will probably want to create your own exception types to handle situation specific to your applications. This is quite easy to do: just define a subclass of Exception. The following example declares a new subclass of Exception and then uses that subclass to signal an error condition in a method. private int detail; myexception(int a){ detail=a; }

Class myexception extends Exception {

public String toString(){


return MyException [ + detail +]; } }

Class exceptiondemo {

static void compute(int a) throws myexception {


S.o.p(Called Compute(+a+)); if (a>10) throw new myexception(a); S.o.p(Normal Exit); } p s v m(S args[]) {

try{
cmpute(1); compute(20); }catch (myexception e){ S.o.p(Caught +e); } } }

Chained Exception

The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception.

For example, imagine a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.
However, the actual cause of the problem was that an I/O error occurred, which caused the divisor to be set improperly.

Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that underlying cause was an I/O error.
Chained Exception let you handle this, any any other situation in which layers of exception exist. The chained exception methods added to Throwable are getCause() and initCause(). 1. Throwable getCause() 2. Throwable initCause(Throwable causeExc)

The getCause() method returns the exception that underlies the current exception. If there is no underlying exception , null is returned. The initCause() method associated causeExc with the invoking exception and returns a reference to the exception.

// Demonstrate exception chaining. Class ChainExcDemo{ static void demoproc(){ //crete an exception NullPointerException e = new NullPointerException(Top layer); /*add a cause*/ e.initCause(new ArithmeticException(Cause);

trrow e;
} p s v m(S args[]){ try{ demoproc(); }catch(NullPointerException e){ /*display top level exception*/ S.o.p(Caught: + e); /*display cause exception*/ S.o.p(Original Cause: + e.getCause()); } } }

You might also like