Lecture 11 - Exception Handling
Lecture 11 - Exception Handling
Programming
Lecture # 11: Exception Handling
Muhammad Imran
(Based on Java, The Complete Reference)
http://www.secscourses.tk
1
Outline
• Exception
• Exception Handling Fundamentals
• Exception Types
• Uncaught Exceptions
• Using try and catch
• Multiple catch Clauses
• throw
• throws
• finally
2
Exception
• An exception is an abnormal condition that arises in a code
sequence at runtime
• An exception is a runtime error
• In OO terms, an exception is an object that describes an exceptional
condition that has occurred in a piece of code
• When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the
error
That method may choose to handle the exception itself, or pass it on.
Either way, at some point the exception is caught and processed.
3
Exception-Handling Fundamentals
4
Exception-Handling Fundamentals
7
Exception Types
• There is an important subclass of Exception, called
RuntimeException.
8
Uncaught Exceptions
• Before we learn how to handle exceptions in our program, it is
useful to see what happens when we don’t handle them.
• Example: divide-by-zero error.
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
} When the Java runtime system
} detects an attempt to divide by
zero, it constructs a new
exception object and then
throws this exception.
12
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 ourselves
• Doing so provide two benefits:
It allows us to fix the error
It prevents the program from automatically terminating
• To guard against and handle a runtime error, simply enclose the
code that we want to monitor inside a try block.
• Immediately following the try block, includes a catch clause that
specifies the exception type that we want to catch.
13
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
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
} Division by zero.
} After catch statement.
14
Using try and catch
• Once an exception is thrown, program control transfers out
of the try block into the catch block
• Catch is not “called”, so execution never “returns” to the try
block from a catch
• Once the catch statement has been executed, program
control continues with the next line in the program following
the entire try/catch mechanism
• 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
15
Using try and catch
18
Multiple Catch Clauses
class MultiCatch { System.out.println("Divide by 0: " +
public static void main(String e);
args[]) { }
try { catch(ArrayIndexOutOfBoundsExce
int a = args.length; ption e) {
System.out.println("a = "+a); System.out.println("Array index
int b = 42 / a; oob: " + e);
int c[] = { 1 }; }
c[42] = 99; System.out.println("After
try/catch blocks.");
} }
catch(ArithmeticException e) }
{
D:\>java MultiCatch
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
20
Multiple Catch Clauses
/* This program contains an error. */
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.");
}
catch(ArithmeticException e) { //ERROR-unreachable
System.out.println("This is never reached.");
}
}
} 21
throw
• It is possible for our program to throw an exception
explicitly, using the throw statement
• The general form of throw is:
throw ThrowableInstance;
• 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
22
throw
• 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 default exception handler halts the
program and prints the stack trace
23
throw
class ThrowDemo { // Demonstrate throw.
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
Caught inside demoproc.
}
Recaught: java.lang.NullPointerException: demo
24
throw
• All built-in runtime exceptions have two constructors:
No parameter
A string parameter
• When the 2nd form is used, the argument specifies a string that
describes the exception
• This string is displayed when the object is used as an argument to
print() or println()
• It can also be obtained by a call to getMessage(), which is defined by
Throwable
25
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 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
RuntimeException, or any of its subclasses.
• All other exceptions that a method can throw must be
declared in the throws clause.
• If they are not, a compiler-time error will result.
26
throws
• The general form of a method declaration that
includes a throws clause
type method-name(parameter-list) throws exception-list
{
//body of method
}
• exception-list is a comma-separated list of
exceptions that a method can throw
27
throws
30
finally
• finally creates a code block 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
31
finally
• The finally clause is optional
32
finally
// 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");
}
}
33
finally
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");
}
}
34
finally
// Execute a try block normally. catch (Exception e) {
static void procC() {
try { System.out.println("Exceptio
System.out.println("inside n caught");
procC"); }
} procB();
finally {
System.out.println("procC's procC();
finally"); }
} }
}
public static void main(String
args[]) { inside procA
procA's finally
try {
Exception caught
procA(); inside procB
} procB's finally
inside procC
procC's finally
35
Recommended Readings
• Page # 213 to 226, Chapter # 10: Exception Handling from
Herbert Schildt, Java: The Complete Reference, J2SETM 9th
Edition
36