0% found this document useful (0 votes)
20 views

Lecture 11 - Exception Handling

This document provides an overview of exception handling in Java. It discusses key concepts like try, catch, throw, throws and finally blocks. Specifically, it covers: 1) How exceptions work in Java and the exception hierarchy rooted in the Throwable class. 2) The fundamentals of exception handling using try, catch, throw, throws and finally keywords. 3) Examples of uncaught exceptions and how they terminate a program unless handled. 4) Demonstrations of using try and catch blocks to guard against errors and continue execution.

Uploaded by

Muhammad Tayyab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lecture 11 - Exception Handling

This document provides an overview of exception handling in Java. It discusses key concepts like try, catch, throw, throws and finally blocks. Specifically, it covers: 1) How exceptions work in Java and the exception hierarchy rooted in the Throwable class. 2) The fundamentals of exception handling using try, catch, throw, throws and finally keywords. 3) Examples of uncaught exceptions and how they terminate a program unless handled. 4) Demonstrations of using try and catch blocks to guard against errors and continue execution.

Uploaded by

Muhammad Tayyab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CSE205: Object Oriented

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

• Exceptions can be generated by the Java runtime


system, or they can be manually generated by our
code
 Exceptions thrown by Java relate to fundamental errors
that violate the rules of the Java language or the
constraints of the Java execution environment
 Manually generated exceptions are typically used to
report some error condition to the caller of a method

4
Exception-Handling Fundamentals

• Java exception handling is managed via five keywords:


try, catch, throw, throws, & finally
 try: Program instructions that we want to monitor for
exceptions are contained within a try block
 catch: Our code can catch an exception (using catch) and can
handle it in some rational manner
 throw: To manually throw an exception, we use the keyword
throw
 throws: Any exception that is thrown out of a method must be
specified as such by a throws clause
 finally: Any code that absolutely must be executed before a
method returns is put in a finally block
5
Exception-Handling Fundamentals
• 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 before try block ends
}
6
Exception Types
• All exception types are subclasses of the built-in class Throwable.
• Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches
• One branch is headed by Exception
 This class is used for exceptional conditions that user programs should
catch
 This is also the class that we will subclass to create our own custom
exception types
• The 2nd branch is topped by Error, which defines exceptions that
are not expected to be caught under normal circumstances by our
program
 Exception of type Error are used by the Java runtime system to
indicate errors having to do with the runtime environment, itself,
e.g., Stack overflow

7
Exception Types
• There is an important subclass of Exception, called
RuntimeException.

• Exceptions of this type are automatically defined for the


programs that we write and include things such as division
by zero and invalid array indexing.

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.

Exception in thread "main" java.lang.ArithmeticException: / by


zero at Exc0.main(Exc0.java:4)
9
Uncaught Exceptions

• Throwing of an exception from a program causes the


execution of it to stop, because once an exception has
been thrown, it must be caught by an exception handler
and dealt with immediately.
• If we haven’t supplied any exception handlers of our own,
then the exception is caught by the default handler
provided by the Java runtime system.
 the default handler displays a string describing the
exception
 prints a stack trace from the point at which the
exception occurred
 and terminates the program
10
Uncaught Exceptions

• An entry in a stack trace includes class name, method


name, filename, and line number
• Example:
 Exception in thread "main" java.lang.ArithmeticException: / by
zero at Exc0.main(Exc0.java:4)
 ArithmeticException is a subclass of RuntimeException, which
more specifically describes what type of error happened
• Java supplies several built-in exception types that match
the various sorts of runtime errors that can be
generated.
• The stack trace will always show the sequence of method
invocation that led up to the error.
11
Uncaught Exceptions

• The same error but in a method separate from main().


class Exc1 {
static void subroutine() { The bottom of the
int d = 0; stack is main’s line 7,
which is the call to
int a = 10 / d;
subroutine(), which
} caused the exception
public static void main(String args[]) { at line 4.
Exc1.subroutine();
}
}
• Exception in thread "main" java.lang.ArithmeticException: / by
zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:7)

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

// Handle an exception and catch(ArithmeticException e) {


move on. System.out.println("Division
import java.util.Random; by zero.");
class HandleError { a = 0; // set a to zero and
public static void main(String //continue
args[]) { }
int a=0, b=0, c=0;
System.out.println("a: " + a);
Random r = new Random();
}//end of for loop
for(int i=0; i<32000; i++) {
try { }//end of main
b = r.nextInt(); }//end of class
c = r.nextInt();
a = 12345 / (b/c);
}
16
Using try and catch
• Throwable overrides the toString() method (defined by
Object) so that it returns a string containing a description of
the exception
• We can display this description in a println() statement by
simply passing the exception as an argument
• Example:
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
Exception: java.lang.ArithmeticException: / by zero
17
Multiple Catch Clauses
• In some cases, more than one exceptions could be
raised by a single piece of code.
• We can specify more than one 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 block executes, the others are bypassed,
and execution continues after the try/catch block

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.

D:\>java MultiCatch TestArg


a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks. 19
Multiple Catch Clauses
• When we use multiple catch blocks, it is important to
remember that exception subclasses must come
before any of their superclasses
• This is because a catch block that uses a superclass
will catch exceptions of that type plus any of its
subclasses
• Thus, a subclass would never be reached if it came
after its superclass
• Unreachable code is a compile time error

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

// This program contains a compile-time error


class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
} ThrowsDemo.java:5: unreported exception
java.lang.IllegalAccessException; must be caught or declared to be thrown
throw new IllegalAccessException("demo");
28
throws
// This is now correct.
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);
}
}
} Inside throwOne.
Caught java.lang.IllegalAccessException:
29
finally
• When exceptions are thrown, execution in a method takes
a rather abrupt, nonlinear path that alters the normal flow
through the method
• Depending upon how the method is coded, it is even
possible for an exception to cause the method to return
prematurely
• This could be a problem in some methods.
 Example: if a method opens a file upon entry and closes it upon
exist, then we will not want the code that closes the file to be
bypassed by the exception-handling mechanism
• The finally keyword is designed to address this contingency

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

• However, each try statement requires at least one catch


or a finally clause

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

You might also like