PAGE-13

CHAPTER-5(Exception Handling)        

       BOTTOM

 

Exception

An exception in java is a signal that indicates the occurance of some unexpected condition during execution of the programe. exception etc.We do not need to provide an explicit checks or Code to handle the exception like “C” language. Java provides an automatic exception handler to deal with the errors or exception.

The exception mechanism built around five keywords.
1.try
2.catch
3.throw
4.throws
5.finally

A try keyword is used to monitor the code which might cause an error or throw an exception .We put that code inside a try block.

catch keyword is used to handle those exceptions which are thrown within the try block.

throws keyword is used when we want the caller of the method to handle the exceptions that a method might throw. The throws clause is specified in the header of the method specifying the exceptions it might throw.

 throw keyword:- throw keyword is used when want to handle the exception explicitely and do not want to handle the exception the default handler.Basically throw keyword explicitely handles the flow of control of the program.

finally:-finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause.

 

This is the general form of an exception-handling block:-

try {

// block of code to monitor for errors

}
catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

}
catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

}
finally {

// block of code to be executed before try block ends}


Here, ExceptionType is the type of exception that has occurred.

 

Exception types:-

Exception

 

Exceptions in Java are objects. All exceptions are derived from the java.lang.Throwable class. The two main subclasses Exception and Error constitute the main categories of throwable exceptions.

 Class Exception


The class Exception represents exceptions that a program would want to be made aware of during execution. Its subclass RuntimeException represents many common programming errors that occur at runtime.Other subclasses of the Exception class define other categories of exceptions, for example, I/O-related  exceptions(IOException, FileNotFoundException, EOFException) etc.

 

Class Error

The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.

 

Class RuntimeException

Runtime exceptions, like out-of-bound array indices (ArrayIndexOutOfBounds Exception), uninitialized references (NullPointerException),illegal casting of references (ClassCastException), illegal parameters llegalArgumentException), division by zero (ArithmeticException),and number format problems (NumberFormatException) are all subclasses of the java.lang.RuntimeException class, which is a subclass of
the Exception class. As these runtime exceptions are usually caused by program bugs that should not occur in the first place, it is more appropriate to treat them as faults in the program design, rather than merely catching them during program execution.

Exception Inheritance hierarchy

 

Checked and Unchecked Exceptions

Except for RuntimeException, Error, and their subclasses, all exceptions are called checked exceptions. The compiler ensures that if a method can throw a checked exception, directly or indirectly, then the method must explicitly deal with it. The method must either catch the exception and take the appropriate action, or pass the exception on to its caller .

Exceptions defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions, meaning that a method is not deal with these kinds of exceptions. They are either irrecoverable
(exemplified by the Error class) and the program should not attempt to deal with them, or they are programming errors by the RuntimeException class) and should be dealt with as such by the java runtme envirement.

 

       Using try and catch

 Although the default exception handler provided by the Java run-time system is useful for debugging, we will usually want to handle an exception according to our requirement.Doing so provides two benefits.

1. it allows you to fix the error.
2. it prevents the program from automatically terminating.

 it is quite easy to do this, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. To illustrate how easily this can be done, the following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error.

 

class ExeptionHandling1 {

public static void main(String args[]) {
int a,b  ;

try {                 // monitor a block of code.
a = 0;
b = 42 / a;
System.out.println("This will not be printed.");

}
 catch (ArithmeticException e) {       // catch divide-by-zero error

System.out.println("Division by zero.");
}

System.out.println("After catch statement.");
}
}

Output ofthis program :-

Division by zero.
After catch statement.

Explaination:-

Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block.

Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.

 

            Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the  exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is popped and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are checked. If no catch statement matches, then the Java run-time system will handle the exception. Here is an example that uses nested try statements:

 

// An example of nested try statements.
class NestedTryExample {
public static void main(String args[]) {
try {
int counter = args.length;

/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */

int b = 100 / counter;
System.out.println("Value of counter = " + counter);
try {      // nested try block

/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */

if(counter==1)
counter = counter/(counter-counter); // division by zero

/* If two command-line args are used,
then generate an out-of-bounds exception. */

if(counter==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

Below is the output based on different inputs:-

C:\>java NestedTryExample

Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestedTryExample One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero

C:\>java NestedTryExample One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
 

All the cases are handeld above.As we can see that different catch block is executed based on different exceptions occurred in the try block.

throw


When we do  want  our program to throw an exception explicitly, then we use the throw statement. The general form of throw is shown here:


throw ThrowableInstance;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways you can obtain.
a Throwable object: using a parameter into a catch clause, or creating one with the new operator.
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. Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.

// Demonstrate throw.
class ThrowExample {
static void  throwdemo() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside throwdemo.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
throwdemo ();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

This program gets two chances to deal with the same error. First, main( ) sets up an exception context and then calls throwdemo ( ). The throwdemo ( ) method then sets up another exception-handling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown.

Here is the output:

Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo}


The version of show( ) in B takes a string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding takes place.

throws

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of 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.
This is the general form of a method declaration that includes a throws clause:


type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.

Example:-Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the program does not specify a throws clause to declare this fact, the program will not compile.


// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}


To make this example compile, you need to make two changes. First, you need to declare that throwOne( ) throws IllegalAccessException. Second, main( ) must define a try/catch statement that catches this exception.

The corrected example is shown here:-


// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}


Here is the output generated by running this example program:

inside throwOne
caught java.lang.IllegalAccessException: demo

finally

Example:-

// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}


In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause is executed on the way out. procB( )’s try statement is exited via a return statement. The finally clause is executed before procB( ) returns. In procC( ), the try statement executes normally, without error. However, the finally block is still executed.

 


              Creating Your Own Exception Subclasses

Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement anything—it is their existence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them.

The following example declares a new subclass of Exception and then uses that subclass to signal an error condition in a method. It overrides the toString( ) method, allowing the description of the exception to be displayed using println( ).

// This program creates a custom exception type.

class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");


Note :
After Successful completion of Training Candidate will be provided with Project Report and Training Certificate.

Home  |   FeedBack  |   Terms of Use  |   Contact Us  |   Report Error
                                                                            Copyright © 2009 R.M Infotech (P) Ltd.                                             Designed by: Raman