Chapter 14 - Exception Handling

Download Report

Transcript Chapter 14 - Exception Handling

Exception Handling
Introduction
• Errors can be dealt with at place error occurs
– Easy to see if proper error checking implemented
– Harder to read application itself and see how code works
• Exception handling
– Makes clear, robust, fault-tolerant programs
– Java removes error handling code from "main line" of program
• Common failures
–
–
–
–
Memory exhaustion
Out of bounds array subscript
Division by zero
Invalid method parameters
Introduction
• Exception handling
– Catch errors before they occur
– Deals with synchronous errors (i.e., divide by zero)
– Does not deal with asynchronous errors
• Disk I/O completions, mouse clicks - use interrupt processing
– Used when system can recover from error
• Exception handler - recovery procedure
• Error dealt with in different place than where it occurred
– Useful when program cannot recover but must shut down
cleanly
Introduction
• Exception handling
– Should not be used for program control
• Not optimized, can harm program performance
– Improves fault-tolerance
• Easier to write error-processing code
• Specify what type of exceptions are to be caught
– Another way to return control from a function or block of
code
When Exception Handling Should
Be Used
• Error handling used for
– Processing exceptional situations
– Processing exceptions for components that cannot handle
them directly
– Processing exceptions for widely used components
(libraries, classes, methods) that should not process their
own exceptions
– Large projects that require uniform error processing
The Basics of Java Exception Handling
• Exception handling
– Method detects error which it cannot deal with
• Throws an exception
– Exception handler
• Code to catch exception and handle it
– Exception only caught if handler exists
• If exception not caught, block terminates
The Basics of Java Exception Handling
• Format
– Enclose code that may have an error in try block
– Follow with one or more catch blocks
• Each catch block has an exception handler
– If exception occurs and matches parameter in catch block
• Code in catch block executed
– If no exception thrown
• Exception handling code skipped
• Control resumes after catch blocks
try{
code that may throw exceptions
}
catch (ExceptionType ref) {
exception handling code
}
The Basics of Java Exception Handling
• Termination model of exception handling
– throw point
• Place where exception occurred
• Control cannot return to throw point
– Block which threw exception expires
– Possible to give information to exception handler
An Exception Handling Example:
Divide by Zero
• Example program
– User enters two integers to be divided
– We want to catch division by zero errors
– Exceptions
• Objects derived from class Exception
– Look in Exception classes in java.lang
• Nothing appropriate for divide by zero
• Closest is ArithmeticException
• Extend and create our own exception class
An Exception Handling Example:
Divide by Zero
5 public class DivideByZeroException
6
extends ArithmeticException {
7
public DivideByZeroException()
12
public DivideByZeroException( String message )
– Two constructors for most exception classes
• One with no arguments (default), with default message
• One that receives exception message
• Call to superclass constructor
– Code that may throw exception in try block
– Error handling code in catch block
– If no exception thrown, catch blocks skipped
1
// Fig. 14.1: DivideByZeroException.java
2
// Definition of class DivideByZeroException.
3 // Used to throw an exception when a
4
// divide-by-zero is attempted.
5
public class DivideByZeroException
6
extends ArithmeticException {
7
public DivideByZeroException()
8
{
9
10
super( "Attempted to divide by zero" );
}
11
12
public DivideByZeroException( String message )
13
{
14
15
16 }
17
Arithmetic
Default constructor
(default message)
Exception)
and customizable
message
constructor.
1.2 Constructors
1.3 super
super( message );
}
1. Class
Define our own DivideByZero
exception class
(exceptions are thrown
objects).
Exception
(extends
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Fig. 14.1: DivideByZeroTest.java
// A simple exception handling example.
// Checking for a divide-by-zero-error.
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DivideByZeroTest extends JFrame
implements ActionListener {
private JTextField input1, input2, output;
private int number1, number2;
private double result;
// Initialization
public DivideByZeroTest()
{
super( "Demonstrating Exceptions" );
Container c = getContentPane();
c.setLayout( new GridLayout( 3, 2 ) );
c.add( new JLabel( "Enter numerator ",
SwingConstants.RIGHT ) );
input1 = new JTextField( 10 );
c.add( input1 );
c.add(
new JLabel( "Enter denominator and press Enter ",
SwingConstants.RIGHT ) );
1. Set up GUI
48
49
input2 = new JTextField( 10 );
c.add( input2 );
50
51
52
53
54
55
56
input2.addActionListener( this );
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
2. Process GUI events
c.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
output = new JTextField();
c.add( output );
2.1 try block
setSize( 425, 100 );
show();
}
// Process GUI events
Notice
public void actionPerformed( ActionEvent e )
enclosing try block. If an exception is
thrown in the block (even from a method call),
the entire block is terminated.
{
DecimalFormat precision3 = new DecimalFormat( "0.000" );
output.setText( "" ); // empty the output JTextField
try {
number1 = Integer.parseInt( input1.getText() );
number2 = Integer.parseInt( input2.getText() );
result = quotient( number1, number2 );
output.setText( precision3.format( result ) );
}
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
catch blocks have error handling
catch ( NumberFormatException nfe ) {
JOptionPane.showMessageDialog( this,
code. Control resumes after the
"You must enter two integers",
catch blocks.
"Invalid Number Format",
The first block
sure
the
JOptionPane.ERROR_MESSAGE );
2.2makes
catch
blocks
}
inputs are of the correct type.
catch ( DivideByZeroException dbze ) {
3. quotient
JOptionPane.showMessageDialog( this, dbze.toString(),
"Attempted to Divide by Zero",
JOptionPane.ERROR_MESSAGE );
4. main
}
}
// Definition of method quotient. Used to demonstrate
// throwing an exception when a divide-by-zero error
// is encountered.
public double quotient( int numerator, int denominator )
throws DivideByZeroException
{
if ( denominator == 0 )
Method quotient throws an
throw new DivideByZeroException();
DivideByZeroException
return ( double ) numerator / denominator;
}
public static void main( String args[] )
{
DivideByZeroTest app = new DivideByZeroTest();
exception (object) if
denominator == 0.
106
app.addWindowListener(
107
new WindowAdapter() {
108
public void windowClosing( WindowEvent e )
109
{
110
e.getWindow().dispose();
111
System.exit( 0 );
112
}
113
}
114
115
);
}
116 }
Program Output
Program Output
Try Blocks
• Exceptions that occurs in a try block
– Usually caught by handler specified by following catch
block
try{
code that may throw exceptions
}
catch ( ExceptionType ref ) {
exception handling code
}
• Can have any number of catch blocks
– If no exceptions thrown, catch blocks skipped
Throwing an Exception
• throw
– Indicates exception has occurred (throwing an exception)
– Operand
• Object of any class derived from Throwable
95
96
if ( denominator == 0 )
throw new DivideByZeroException();
– Derived from Throwable:
• Exception - most programmers deal with
• Error - serious, should not be caught
• When exception thrown
– Control exits current try block
– Proceeds to catch handler (if exists)
Throwing an Exception
• Exceptions
– Can still throw exceptions without explicit throw statement
• ArrayIndexOutOfBoundsException
– Terminates block that threw exception
Catching an Exception
• catch blocks
– Contain exception handlers
– Format:
catch( ExceptionType ref ) {
error handling code
}
82
catch ( DivideByZeroException dbze ) {
83
JOptionPane.showMessageDialog( this,
dbze.toString(),
84
"Attempted to Divide by Zero",
85
JOptionPane.ERROR_MESSAGE );
86
}
– To catch all exceptions, catch an exception object:
catch( Exception e )
Catching an Exception
• Catching exceptions
– First handler to catch exception does
• All other handlers skipped
– If exception not caught
• Searches enclosing try blocks for appropriate handler
try{
try{
throw Exception2
}
catch ( Exception1 ){...}
}
catch( Exception2 ){...}
– If still not caught, applications terminate
Catching an Exception
• Information
– Information can be passed in the thrown object
• If a catch block throws an exception
– Exception must be processed in the outer try block
• Usage of exception handlers
– Rethrow exception (next section)
• Convert exception to different type
– Perform recovery and resume execution
– Look at situation, fix error, and call method that generated
exception
– Return a status variable to environment
Rethrowing an Exception
• Rethrowing exceptions
– Use if catch handler cannot process exception
– Rethrow exception with the statement:
throw e;
• Detected by next enclosing try block
– Handler can always rethrow exception, even if it performed
some processing
Throws Clause
• Throws clause
– Lists exceptions that can be thrown by a method
int g( float h ) throws a, b, c
{
// method body
}
92
93
public double quotient( int numerator, int denominator )
throws DivideByZeroException
– Method can throw listed exceptions
Throws Clause
• Run-time exceptions
– Derive from RunTimeException
– Some exceptions can occur at any point
• ArrayIndexOutOfBoundsException
• NullPointerException
– Create object reference without attaching object to
reference
• ClassCastException
– Invalid casts
– Most avoidable by writing proper code
Throws Clause
• Checked exceptions
– Must be listed in throws clause of method
– All non-RuntimeExceptions
• Unchecked exceptions
– Can be thrown from almost any method
• Tedious to write throws clause every time
• No throws clause needed
– Errors and RunTimeExceptions
Throws Clause
• Catch-or-declare requirement
– If method calls another method that explicitly throws
checked exceptions
• Exceptions must be in original method's throws clause
– Otherwise, original method must catch exception
– Method must either catch exception or declare it in the
throws clause
Exceptions and Inheritance
• Inheritance
– Exception classes can have a common superclass
– catch ( Superclass ref )
• Catches subclasses
• "Is a" relationship
– To catch all exceptions, catch an exception object:
catch( Exception e )
– Polymorphic processing
– Easier to catch superclass than catching every subclass
finally Block
• Resource leaks
– Programs obtain and do not return resources
– Automatic garbage collection avoids most memory leaks
• Other leaks can still occur
• finally block
– Placed after last catch block
– Can be used to returns resources allocated in try block
– Always executed, irregardless whether exceptions thrown or
caught
– If exception thrown in finally block, processed by
enclosing try block
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 14.9: UsingExceptions.java
// Demonstration of stack unwinding.
public class UsingExceptions {
public static void main( String args[] )
{
1. main
try {
Call method throwException
throwException();
(enclosed in a try block).
1.1 throwException
}
catch ( Exception e ) {
Throw
Exception.
The catch block
System.err.println( "Exception handled in
main"an);
1.2 catch
}
cannot handle it, but the finally block
}
executes irregardless.
public static void throwException() throws Exception
{
// Throw an exception and catch it in main.
try {
System.out.println( "Method throwException" );
throw new Exception();
// generate exception
}
catch( RuntimeException e ) { // nothing caught here
System.err.println( "Exception handled in " +
"method throwException" );
}
finally {
System.err.println( "Finally is always executed" );
}
}
}
2. Define
throwException
2.1 try
2.2 catch
2.3 finally
Method throwException
Finally is always executed
Exception handled in main
Program Output
Using printStackTrace and
getMessage
• Class Throwable
– Superclass of all exceptions
– Offers method printStackTrace
• Prints method call stack for caught Exception object
– Most recent method on top of stack
• Helpful for testing/debugging
– Constructors
• Exception()
• Exception( String informationString )
– informationString may be accessed with method
getMessage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 14.10: UsingExceptions.java
// Demonstrating the getMessage and printStackTrace
// methods inherited into all exception classes.
public class UsingExceptions {
public static void main( String args[] )
1. main
Call method1, which calls
{
try {
method2, which calls method3,
method1();
1.1 try
which throws an exception.
}
catch ( Exception e ) {
System.err.println( e.getMessage() + "\n" );
1.2 getMessage
e.printStackTrace();
}
}
getMessage prints the 1.3
String
the
printStackTrace
Exception was initialized with.
public static void method1() throws Exception
{
printStackTrace
method2();
order:
}
method3
public static void method2() throws Exception
method2
{
method1
method3();
}
main
(order they were called
public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
}
}
2. method1
prints the methods in this
3. method2
4. method3
4.1 throw
when exception occurred)
Exception thrown in method3
java.lang.Exception: Exception thrown in method3
at UsingExceptions.method3(UsingExceptions.java:28)
at UsingExceptions.method2(UsingExceptions.java:23)
at UsingExceptions.method1(UsingExceptions.java:18)
at UsingExceptions.main(UsingExceptions.java:8)
Program Output