Exception Handling
Exception Handling
Exception-Handling Fundamentals
• Exception: an abnormal condition that arises in a
code sequence at run time/ run time error
– Java exception is an object that describes an
exceptional (that is, error) condition
– When an exceptional condition arises, an object
representing that exception is created and thrown in
the method that caused the error
• Exception can be
– generated by the Java run-time system (relate to
fundamental errors that violate the rules of the Java
language)
– Manually generated (typically used to report some
error condition to the caller of a method)
2
Keywords for exception handling
• try block contains program statements that are to
be to monitored for exceptions
– If an exception occurs within the try block, it is thrown
• catch block contain statements that catch
this exception and handle it in some rational
manner
– System-generated exceptions are automatically thrown by
the Java runtime system.
• throw is used to manually throw an exception
• throws clause is used to specify any exception
that is thrown out of a method
• finally block contains code that absolutely must
be executed after a try block completes 3
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 after try block ends
}
4
Exception Types
• All exception types are subclasses
of the built-in class Throwable
• Below Throwable are two
subclasses that partition
exceptions into two branches
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
6
Using try and catch
• Exception handling benefits
– allows you to fix the error
– prevents the program from automatically terminating
class Exc2 {
public static void main(String args[]) {
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.");
} 7
}
Using try and catch
class Exc2 {
public static void main(String args[])
{ 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.");
}
} OUTPUT
} System.out.println("After catch
Division by zero.
statement.");
After catch statement.
8
Another Example
// Handle an exception and move
on. import java.util.Random;
class HandleError {
public static void main(String args[])
{ int a=0, b=0, c=0;
Random r = new Random(); for(int
i=0; i<32000; i++) { try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
} catch (ArithmeticException e)
{ System.out.println("Division by
zero."); a = 0; // set a to zero and
continue
}
System.out.println("a: " + a);
}
}
}
9
Displaying a Description of an
Exception
• Throwable overrides the toString( ) method
(defined by Object) so that it returns a
string containing a description of the
exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
OUTPUT
Exception: java.lang.ArithmeticException: / by zero
10
Multiple catch Clauses
• Use when more than one exception could be
raised by a single piece of code
• 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
– All others are bypassed
– execution continues after the try / catch block
• NOTE: exception subclasses must come before any of their superclasses
because a catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses
11
Multiple catch Clauses (Example)
class MultipleCatches {
public static void main(String args[]) {
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.");
}
}
12
Multiple catch Clauses (Example)
OUTPUT
C:\>java MultipleCatches
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:\>java MultipleCatches TestArg
a=1
Array index oob:
java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
13
Nested try Statements
• 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
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
exhausted
• If no catch statement matches, then the Java run-time
system will handle the exception
14
Nested try Statements (Example)
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
if(a==1) a = a/(a-a); // one command-line arg, division by zero
if(a==2) {
int c[] = { 1 };
c[42] = 99; // two command-line args, 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);
}
}
}
15
Nested try Statements (Example)
OUTPUT
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
16
throw
• To throw an exception explicitly, use the throw
statement
– flow of execution stops immediately after the throw
statement
– nearest enclosing try block is inspected to see if it has
a catch statement that matches the type of exception
and control is transferred to that statement
– No match: next enclosing try statement is inspected,
and so on
– no matching catch found in any block:
default exception handler halts the program and
prints the stack trace
17
throw (example)
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e)
{ System.out.println("Caught inside
demoproc."); throw e; // rethrow the exception
}
}
19
throws
• If method can cause an exception that it does
not handle
– Then method’s declaration must include a throws
clause (that lists the types of exceptions that
a method might throw)
– Necessary for all exceptions, except Error or
RuntimeException, or any of their subclasses
20
throws (example)
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
21
throws (example)
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
22
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
– 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
– useful for closing file handles and freeing up any
other resources
– finally clause is optional
23
finally (example)
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA"); throw new RuntimeException("demo");
} finally { System.out.println("procA's finally");}
}
static void procB() {
try {
System.out.print
ln("inside
procB");
return;
} finally {
System.out.printl
n("procB's
finally"); }
}
static void procC() {
try {
System.out.prin
tln("inside
procC");
} finally {
System.out.print
ln("procC's
finally"); }
}
public static void 24
finally (example)
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA"); throw new RuntimeException("demo");
} finally { System.out.println("procA's finally");}
}
static void procB() {
try {
System.out.print
ln("inside
} finally { System.out.println("procB's finally");
} procB"); OUTPUT
} return; inside procA
static void procC() {
try {
procA's finally
System.out.println("inside procC"); Exception caught
} } finally { System.out.println("procC's inside procB
finally");
public static}void main(String args[]) {
try { procB's finally
procA(); inside procC
} catch (Exception e) procC's finally
{ System.out.println("Exception
caught");
}
procB();
procC();
} }
25
Java’s Built-in Exceptions
Java’s Unchecked RuntimeException Subclasses Defined in java.lang
26
Java’s Built-in Exceptions
Java’s Checked Exceptions Defined in java.lang
27