Download Chapter 8

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Exception Handling
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Objectives
• To understand the concept of exception handling when
program execution errors occur.
• To implement exception handling in program execution.
DCS 2133 Object Oriented Programming
Introduction
• A program can be written assuming that nothing unusual or
incorrect will happen.
– The user will always enter an integer when prompted to
do so.
– There will always be a nonempty list for a program that
takes an entry from the list.
– The file containing the needed information will always
exist.
• Unfortunately, it isn’t always so.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Introduction
• Once the core program is written for the usual,
expected case(s), Java’s exception-handling
facilities should be added to accommodate the
unusual, unexpected case(s).
• Exception handling divides a class or method
definition into separate sections:
– one section for the normal case(s)
– another section for the exceptional case(s).
• Depending on how a method is used, special
cases may need to be handled in different ways.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exception
• What is exception? An error condition that can
occur during the normal course of program
execution.
• Exception handling – resolving exceptions that
may occur so program can continue or terminate
gracefully
• Exception handling enables programmers to
create programs that are more robust and faulttolerant.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exception handling
• When an exception occurs, or is thrown, the
normal sequence of flow is terminated. The
exception-handling routine is then executed; we
say the thrown exception is caught.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Example of No Catching Exceptions
String inputStr;
int
age;
inputStr = JOptionPane.showInputDialog(null, "Age:");
age
= Integer.parseInt(inputStr);
Error message for invalid input
java.lang.NumberFormatException: ten
at java.lang.Integer.parseInt(Integer.java:405)
at java.lang.Integer.parseInt(Integer.java:454)
at Ch8Sample1.main(Ch8Sample1.java:20)
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example
• Simple example
– Suppose the students are hosting an event to express
appreciation to their lecturer, at which donuts and milk
will be served.
– If the number of donuts is known, and the number of
glasses of milk is known, it should be possible to
calculate the number of donuts per class of milk.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example, cont.
• Simple example, cont.
– But what if there is no milk because the cows are on
strike?
– An attempt to divide the number of donuts by the
number of glasses of milk will result in an attempt to
divide by zero.
– This would be an complete disaster, known in Java as
an exception.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example, cont.
• In Java, it is possible to test for this unusual situation using
an if-else statement, for example.
• class GotMilk
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example, cont.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example, cont.
• In Java, it is also possible to throw an exception.
class ExceptionDemo
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example,
cont.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java: Example,
cont.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java
• Exceptions are handled using a
threesome.
• try
try-throw-catch
block syntax
try
{
Code_to_Try
Throw_An_Exception_Or_Invoke_A_Method
_That_Might_Throw_An_Exception
Possibly_More_Code
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exceptions in Java
• try block – encloses code that might throw an
exception and the code that should not execute if
an exception occurs
• Consists of keyword try followed by a block of
code enclosed in curly braces
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Catching Exceptions
• catch block – catches (i.e., receives) and handles an
exception, contains:
– Begins with keyword catch
– Exception parameter in parentheses – exception parameter
identifies the exception type and enables catch block to interact
with caught exception object
– Block of code in curly braces that executes when exception of
proper type occurs
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Catching an exception using try – catch block
inputStr = JOptionPane.showInputDialog(null, "Age:");
try {
age = Integer.parseInt(inputStr);
try
} catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "’" + inputStr
catch
+
"‘ is invalid\n"
+
"Please enter digits only");
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
try-catch Control Flow
Exception
try {
<t-stmt-1>
<t-stmt-2>
No Exception
try {
<t-stmt-1>
<t-stmt-2>
Assume <t-stmt-3>
throws an exception.
<t-stmt-3>
<t-stmt-4>
. . .
<t-stmt-n>
<t-stmt-3>
} catch (Exception e) {
<c-stmt-1>
. . .
<c-stmt-m>
}
<next stmt>
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
<t-stmt-4>
Remaining
statements in the
try block is skipped.
. . .
<t-stmt-n>
} catch (Exception e) {
<c-stmt-1>
Statements in the
catch block are
executed.
And the execution
continues to the
next statement
All statements in
the try block are
executed.
. . .
<c-stmt-m>
}
<next stmt>
DCS 2133 Object Oriented Programming
Statements in the
catch block are
skipped.
Using try-catch statement in a loop
while (true){
inputStr = JOptionPane.showInputDialog(null, "Age:");
try {
age = Integer.parseInt(inputStr);
return age;
try
} catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "’" + inputStr
catch
+
"‘ is invalid\n"
+
"Please enter digits only");
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Another Example –
Divide by Zero Exception
public static int quotient( int numerator, int denominator )
{
return numerator / denominator; // possible division by zero
}
public static void main( String args[] )
{
Scanner scanner = new Scanner( System.in );
System.out.print( "Please enter an integer numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Please enter an integer denominator: " );
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n", numerator, denominator, result );
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Getting Information
• There are two methods we can call to get information
about the thrown exception:
– getMessage
– printStackTrace
try {
. . .
} catch (NumberFormatException e){
System.out.println(e.getMessage());
System.out.println(e.printStackTrace());
}
getMessage
ten
java.lang.NumberFormatException: ten
printStacktrace
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
at java.lang.Integer.parseInt....
DCS 2133 Object Oriented Programming
Multiple catch Blocks
• A single try-catch statement can include multiple catch
blocks, one for each type of exception.
try {
. . .
age = Integer.parseInt(inputStr);
. . .
val = cal.get(id); //cal is a GregorianCalendar
. . .
} catch (NumberFormatException e){
. . .
} catch (ArrayIndexOutOfBoundsException e){
. . .
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Multiple catch Control Flow
Exception
try {
<t-stmt-1>
<t-stmt-2>
No Exception
Assume <t-stmt-3>
throws an exception
and <catch-block-3>
is the matching block.
try {
<t-stmt-1>
<t-stmt-2>
<t-stmt-3>
<t-stmt-4>
. . .
<t-stmt-n>
<t-stmt-3>
<t-stmt-4>
Remaining
statements in the
try block is skipped.
}
All statements in
the try block are
executed and throw
no exceptions.
. . .
<t-stmt-n>
}
<catch-block-1>
<catch-block-2>
<catch-block-3>
. . .
<catch-block-m>
}
<catch-block-1>
<catch-block-2>
Statements
in the
matching
catch block
are executed.
<catch-block-3>
. . .
<catch-block-m>
}
<next stmt>
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
<next stmt>
DCS 2133 Object Oriented Programming
All catch
blocks are
skipped.
The finally Block
• There are situations where we need to take certain
actions regardless of whether an exception is
thrown or not.
• We place statements that must be executed
regardless of exceptions in the finally block.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
try-catch-finally Control Flow
Exception
No Exception
Assume <t-stmt-i>
try {
throws an exception
<t-stmt-1>
and <catch-block-i> is
. . .
the matching block.
<t-stmt-i>
. . .
<t-stmt-n>
}
<catch-block-1>
. . .
<catch-block-i>
. . .
<catch-block-m>
try {
<t-stmt-1>
. . .
<t-stmt-i>
. . .
<t-stmt-n>
}
<catch-block-1>
. . .
<catch-block-i>
. . .
<catch-block-m>
} finally {
. . .
}
<next stmt>
} finally {
. . .
}
<next stmt>
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
finally block is
executed.
DCS 2133 Object Oriented Programming
finally block is
executed.
Propagating Exceptions
• Instead of catching a thrown exception by using the trycatch statement, we can propagate the thrown
exception back to the caller of our method.
• The method header includes the reserved word throws.
public int getAge( ) throws NumberFormatException {
. . .
int age = Integer.parseInt(inputStr);
. . .
return age;
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Throwing Exceptions
• We can write a method that throws an exception
directly, i.e., this method is the origin of the exception.
• Use the throw reserved to create a new instance of the
Exception or its subclasses.
• The method header includes the reserved word throws.
public void doWork(int num) throws Exception {
. . .
if (num != val) throw new Exception("Invalid val");
. . .
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Exception Thrower
• When a method may throw an exception, either
directly or indirectly, we call the method an
exception thrower.
• Every exception thrower must be one of two types:
– catcher.
– propagator.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Types of Exception Throwers
• An exception catcher is an exception thrower that
includes a matching catch block for the thrown
exception.
• An exception propagator does not contain a
matching catch block.
• A method may be a catcher of one exception and
a propagator of another.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Sample Call Sequence
Method A
Method B
Method C
try {
try {
try {
B();
} catch (Exception e){
. . .
}
C();
} catch (Exception e){
. . .
}
D();
} catch (Exception e){
. . .
catcher
A
B
A
propagator
C
B
A
Stack Trace
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Method D
if (cond) {
throw
new Exception();
propagator
D
C
B
A
Exception Types
• All types of thrown errors are instances of the
Throwable class or its subclasses.
• Serious errors are represented by instances of the Error
class or its subclasses.
• Exceptional cases that common applications should handle
are represented by instances of the Exception class or its
subclasses.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Throwable Hierarchy
• There are over 60 classes in the hierarchy.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Checked vs. Runtime
• There are two types of exceptions:
– Checked.
– Unchecked.
• A checked exception is an exception that is
checked at compile time.
• All other exceptions are unchecked, or runtime,
exceptions. As the name suggests, they are
detected only at runtime.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Different Handling Rules
• When calling a method that can throw checked
exceptions
– use the try-catch statement and place the call in the try
block, or
– modify the method header to include the appropriate
throws clause.
• When calling a method that can throw runtime
exceptions, it is optional to use the try-catch
statement or modify the method header to include
a throws clause.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Handling Checked Exceptions
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Handling Runtime Exceptions
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Programmer-Defined Exceptions
• Using the standard exception classes, we can use the
getMessage method to retrieve the error message.
• By defining our own exception class, we can pack more
useful information
– for example, we may define a OutOfStock exception class and
include information such as how many items to order
• AgeInputException is defined as a subclass of Exception
and includes public methods to access three pieces of
information it carries: lower and upper bounds of valid age
input and the (invalid) value entered by the user.
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Example – AgeInputException
class AgeInputException extends Exception {
public int lowerBound() {
return lowerBound;
}
private static final String DEFAULT_MESSAGE = "Input
out of bounds";
private int lowerBound;
private int upperBound;
private int value;
public int upperBound() {
return upperBound;
}
public AgeInputException(int low, int high, int input) {
this(DEFAULT_MESSAGE, low, high, input);
}
public AgeInputException(String msg,
int low, int high, int input) {
super(msg);
public int value() {
return value;
}
}
if (low > high) {
throw new IllegalArgumentException();
}
lowerBound = low;
upperBound = high;
value
= input;
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Example – AgeInputVer5
import javax.swing.*;
public int getAge(String prompt) throws AgeInputException {
String inputStr;
int age;
class AgeInputVer5 {
private static final String DEFAULT_MESSAGE = "Your age:";
private static final int DEFAULT_LOWER_BOUND = 0;
private static final int DEFAULT_UPPER_BOUND = 99;
while (true) {
inputStr = JOptionPane.showInputDialog(null, prompt);
try {
age = Integer.parseInt(inputStr);
private int lowerBound;
private int upperBound;
if (age < lowerBound || age > upperBound) {
throw new AgeInputException("Input out of bound",
lowerBound, upperBound, age);
}
return age; //input okay so return the value & exit
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "'" + inputStr
+ "' is invalid\n“ + "Please enter digits only");
}
public AgeInputVer5( ) throws IllegalArgumentException {
setBounds(DEFAULT_LOWER_BOUND,
DEFAULT_UPPER_BOUND);
}
public AgeInputVer5(int low, int high)
throws IllegalArgumentException {
if (low > high) {
throw new IllegalArgumentException(
"Low (" + low + ") was " +
"larger than high(" + high + ")");
} else {
setBounds(low, high);
}
}
}
}
public int getAge() throws AgeInputException {
return getAge(DEFAULT_MESSAGE);
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
private void setBounds(int low, int high) {
lowerBound = low;
upperBound = high;
}
}
DCS 2133 Object Oriented Programming
Example -AgeInputExceptionDemo
import javax.swing.*;
class Ch8TestAgeInputVer5 {
public static void main( String[] args ) {
int entrantAge;
try {
AgeInputVer5 input = new AgeInputVer5(25, 50);
entrantAge = input.getAge("Your Age:");
//continue the processing
JOptionPane.showMessageDialog(null, "Input Okay"); //TEMP
} catch (AgeInputException e) {
JOptionPane.showMessageDialog(null, "Error: " + e.value() + " is entered. It is " + "outside the valid range of [" +
e.lowerBound() + ", " + e.upperBound() + "]");
}
}
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming
Sample output
Enter 0
Will produce
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display.
DCS 2133 Object Oriented Programming