10_Exception Handling
10_Exception Handling
Exception
Handling
Chapter 10
• An exception is an abnormal condition that arises in a code
sequence at run time. 2
try{
// block of code to monitor for errors
}
catch (ExceptionTypel exOb) {
// exception handler for ExceptionTypel
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally{
// block of code to be executed before try block ends
}
Exception Types
6
• All exception types are subclasses of the built-in class Throwable.
Throwable
Exceptional conditions that
user programs should
catch
Exception Error
Automatically defined for
the programs that a user
write, for divison by zero,
invalid array indexing….. 1. These are not
expected to caught under
RuntimeException noraml conditions
2. Used by Java run-time
Systems.
3. Stack overflow is an
Example.
Uncaught Exceptions
7
• Before you learn how to handle exceptions in your program, it is
useful to see what happens when you don’t handle them. This
small program includes an expression that intentionally causes a
divide-by-zero error
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 /d ;
System.out.println(“a=”+a);
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
} at Exc0.main(Exc0.java:6)
8
• When the Java run-time system detects the attempt to divide by
zero, it constructs a new exception object and then throws this
exception.
• This causes the execution of Exc0 to stop, because once an
exception has been thrown, it must be caught by an exception
handler and dealt with immediately.
• In this example, we haven’t supplied any exception handlers of
our own, so the exception is caught by the default handler
provided by the Java run-time system
Using try and catch
9
• Although the default exception handler provided by Java run-time
system is useful for debugging, we usually want to handle an
exception ourselves.
• Doing so provides two benefits.
• First, it allows us to fix errors.
• Second, it prevents the program from automatically terminating.
• At the core of exception handling are try and catch. These
keywords work together; you can’t have a try without a catch, or a
catch without a try.
10
class Exc2 {
public static void main(String args[]) { 11
int d, a;
try { // 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.");
}
}
Division by zero.
After catch statement.
Contd…
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.
A try and its catch statement form a unit. The scope of the catch clause is restricted
to those statements specified by the immediately preceding try statement.
A catch statement cannot catch an exception thrown by another try statement (except
in the case of nested try statements, described shortly).
The statements that are protected by try must be surrounded by curly braces. (That is,
they must be within a block.) You cannot use try on a single statement.
The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened.
For example, in the next program each iteration of the for loop obtains two random
integers. Those two integers are divided by each other, and the result is used to divide
the value 12345
13
Contd…
try {
int a = args.length;
system.out.println("a = " + a);
int b = 42 / 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.");
}java MultiCatch a = O Divide by 0: java. lang.ArithmeticException: / by zero After try /catch
} blocks.
java MultiCatch TestArg a = 1 Array index oob: java.lang.ArraylndexOutOfBoundsException
42 After try /catch blocks.
/* This program contains an error. A subclass must come before its
superclass in a series of catch statements. If not, unreachable code
19
will be created and a compile-time error will result. */
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}
Try Blocks Can Be Nested
20
• The try statements can be nested. A try statement can be inside the
block of another try.
• Each time a try statement is entered, the context of that exception
is
pushed on the stack.
• If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and next try statement’s
catch handlers are inspected for a match.
• This continues until the success.
• If no catch statement matches, then the java run-time system will
handle the exception.
// An example nested try statements.
class NestTry
{ 21
if(a==1)
a = a/(a-a); // division by zero
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}catch(ArrayIndexOutOfBoundsException e)
{ 22
{
static void throwOne()
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
throwOne();
}
}
// This is now correct.
class ThrowsDemo
{ 29