2
Objectives
On completion of this period, you would be able
to learn:
•Usage of Java keywords to handle exceptions
3
Recap
In the previous class, you have studied about how to
deal with exception
•If an exception occurs within the try block, it is
thrown
•Your code can catch this exception using catch and
handle it in some rational manner
4
Usage Of Java Keywords To Handle Exceptions
•We know that Java manages exceptions through
five keywords:
•try
•catch
•throw
•throws
•finally
5
Keyword Usage in Exception 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
}
6
Try and Catch
•The default exception handler provided by the
Java run-time system is useful for debugging
•You will want to handle an exception yourself,
for two reasons
1.It allows you to fix the error
2.It prevents the program from automatically terminating
7
Simple Java Program Using try- catch
class ExceptionDemo {
public static void main(String args[]) {
int d, a;
try { // to monitor a block of code.
d = 0;
a = 42 / d;
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.");
}
}
8
Explanation
•This program is trying to divide a value by zero
which is not possible
•Hence the program catch Arithmetic Exception and
is thrown safely without abnormal termination
Example 2
class ExceptionDemo2 {
public static void main (String [] args){
int [] a= new int[3];
try{
for (int i=0; i<=3; i++)
a[i]=i*i;
System. out. println(a[i]);
}
} catch(Exception e){
System.out. println(e);
}
}
}
9
Explanation
•In the above program, an array of size 3 is created
•Within the for loop, the array is initialized with i*i
•When the value of i in 3, on exception occurs, as the
size of array in 3 an its subscript should be less than 3
•An exception, ArrayIndexOutOfBoundsException, is
handled in the catch block
10
Contd . . .
11
Points to Remember
•Generally programmer wants handle exceptions
for himself for two reasons
•One is to fix the error on his own
•Another is to prevent the program to terminate
automatically
•If exception handling mechanism is provided by
the programmer, then debugging could be easy
12
Summary
•In this class we have discussed
•Keywords for Java exception handling
•The usage of the keywords to handle
exceptions
13
Quiz
1.Which of the following is an example for
Arithmetic Exception
A.Null pointer
B.Stackoverflow
C.Divide by zero
D.FileNotFound
2.____ keyword is used to monitor for errors
A.catch
B.try
C.finally
D.throw
14
Quiz
15
Frequently Asked Questions
1.Write a simple java program which demonstrate
the use of try- catch keywords
Assignment
•Modify the program example listed in this
lesson, such that no exception are generated
16