Exception Handling
Error occurred in a program can be of two types: syntax error or logical error.
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.
A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.
Exception Handling is a mechanism by which exception occurred in a program is handled.
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
The general form of an exception-handling block is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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 } |
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy.
The Throwable class has two subclasses Error and Exception.
Error and Exception classes are used for handling errors in java
Unchecked exceptions
Before we learn how to handle exceptions in your program, it is useful to see what happens when we don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error.
error.
1 2 3 4 5 6 7 8 |
class E { public static void main(String args[]) { int x = 0; int y = 1 / x; } } |
Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero
at E.main(E.java:4)
Using try and catch
The following program includes a try block and a catch clause which processes the
ArithmeticException generated by the division-by-zero error.
Demonstration of Division by zero
Exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Ex { public static void main(String args[]) { int x, y; try { x = 0; y= 1/ x; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } } s |
This program generates the following output:
Division by zero.
After catch statement.
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.
In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continu
Demonstration of multiple catch block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 1 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } } |
This program will cause a division-by-zero exception if it is started with no commandline parameters,since a will equal zero. It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the
program attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
throw
So far, you have only been catching exceptions that are thrown by the Java run-time system. However,it is possible for our program to throw an exception explicitly, using 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.
Demonstration of throw statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class ThrowDemo { public static void main(String args[]) { int x=2, y=0; try { if(y==0) throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("Exception Occurred: Division by 0 " + e); } } } |
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. We do this by including throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.
This is the general form of a method declaration that includes a throws clause:
Return_type method-name (parameter-list) throws exception-list
{
// body of method
}
Demonstration of thows statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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); } } } |
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.
Demonstration of finally block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Ex { public static void main(String args[]) { int x, y; try { x = 0; y= 1/ x; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } finally { System.out.println("End of Try/Catch Block"); } } } |
Output:
Division by zero.
End of Try/Catch Block
Java’s Built-in Exceptions
Inside the standard package 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
User Defined Exceptions (VVVI)
Although Java’s built-in exceptions handle most common errors, we will probably want to create our 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).
Demonstration of User Defined Exceptions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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 + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } } |
Assignments
Short Type Questions
1. Differentiate error and exception.
2. What is exception handling mechanism?
3. Can a try block stand alone? Explain with an example.
4. Name the super class of error and exception class.
5. What is Java’s built in exceptions?
6. Name 5 keywords used to handle exception in java.
7. Differentiate between final, finalize and finally.
8. What is ArrayIndexOutOfBoundsException?
9. Which block is always executed, no matter whether exception occurs or not?
a) try b) catch c)finally d)finalize
Long Type Questions
1. Discuss exception handling mechanism.
2. Write a program to evaluate x/y, where x and y are integers using exception handling mechanism.
3. Discuss user defined exception in java with an example.
4. Explain the meaning of each keyword: try, catch, throw, throws and finally.