Professional Documents
Culture Documents
Exception Handling 1
Exception Handling 1
Exception Handling 1
Outline
15.1 Introduction
15.2 Exception-Handling Overview
15.3 Exception-Handling Example: Divide by Zero
15.4 Java Exception Hierarchy
15.5 Rethrowing an Exception
15.6 finally Clause
15.7 Stack Unwinding
15.8 printStackTrace, getStackTrace and getMessage
15.10 Declaring New Exception Types
15.11 Constructors and Exception Handling
1
15.1 Introduction
Exception handling
Exception is an indication of problem during execution
“exception” occurs infrequently
e.g., divide by zero
Promotes robust and fault-tolerant software
Java’s Exception Handling nearly identical to C++
2
15.2 Exception-Handling
Overview
Mixing program code with error-handling code makes
program difficult to read, modify, maintain, debug
Uses of exception handling
Process exceptions from program components
Handle exceptions in a uniform manner in large projects
Remove error-handling code from “main line” of execution
A method detects an error and throws an exception
Exception handler processes the error
Uncaught exceptions yield adverse effects
Might terminate program execution
3
15.2 Exception-Handling
Overview
Code that could generate errors put in try blocks
Code for error handling enclosed in a catch clause
The finally clause always executes
Termination model of exception handling
The block in which the exception occurs expires
immediately
throws clause specifies exceptions method throws (or
by methods it calls)
Simple problems that can easily be fixed can be handled
as “errors”
Use Exception Handling for more complicated situations
4
15.2 Exception-Handling
Overview
Typical exceptions – array index out of range, overflow,
division by zero, invalid method parameters, memory
allocation problems
Most significant use of Exception Handling – problem
occurs in a method, but resolution must be done in
calling method (one or more levels above)
Method that detects problem “throws an exception”
Method that resolves problem “catches the exception”
5
15.3 Exception-Handling
Example: Divide by Zero
Common programming mistake
Throws ArithmeticException
NumberFormatException is thrown if parseInt,
parseDouble, etc. are given bad strings
Program catches an exception in an “appropriate” catch
block (same class or superclass)
Program continues executing with code after the last
catch block (not back inside the try block)
6
1 // Fig. 15.1: DivideByZeroTest.java
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
8 implements ActionListener {
DivideByZeroT
12
13 // set up GUI
14 public DivideByZeroTest()
15 {
est.java
16 super( "Demonstrating Exceptions" );
17
21
23 container.add(
26 container.add( inputField1 );
7
est.java
29
28 // set up label and inputField2; register listener
30 SwingConstants.RIGHT ) );
32 container.add( inputField2 );
33 inputField2.addActionListener( this );
Line 51
34
38 container.add( outputField );
39
41 setVisible( true );
Lines 52-53
42
44
50 JTextFields
// read two numbers and calculate quotient
51 try {
8
Line 60
55
56
54
58
on
62 "You must enter two integers", "Invalid Number Format",
63 JOptionPane.ERROR_MESSAGE );
64 }
65
Line 77
69 arithmeticException.toString(), "Arithmetic Exception",
70 JOptionPane.ERROR_MESSAGE );
71 }
72
74
77
Method quotient
throws ArithmeticException
throws
78 {
ArithmeticExcepti
80 }
on
9
81
83 {
85 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
86 }
87
DivideByZeroT
est.java
10
15.4 Java Exception
Hierarchy
Exceptions (like everything in Java) are objects
Superclass Throwable
Subclass Exception
Exceptional situations
Should be caught by program
Subclass Error
Typically not caught by program
Checked exceptions (include any you create)
“catch or declare” requirement
Unchecked exceptions (subclass of RuntimeException,
e.g., NumberFormatException)
Good idea to catch, but not required
11
Fig. 15.2 Inheritance hierarchy
for class Throwable
Throwable
Exception Error
12
15.5 Rethrowing an
Exception
Rethrow exception if catch cannot handle it
This typically involves a try block (with its catch blocks)
inside another try block
Inner catch block throws it to the outer catch block … or
even on to the calling method
13
15.6 finally Clause
Resource leak
Caused when resources are not released by a program
files, database connections, network connections
The finally block (optional)
Appears after catch blocks
Always executes whether or not any exception is thrown
Use to release resources (e.g., close file)
14
1 // Fig. 15.3: UsingExceptions.java
6 {
7 try {
9 }
10
UsingExceptio
12 catch ( Exception exception ) {
14 }
15
ns.java
16 doesNotThrowException();
17 }
18
19 // demonstrate try/catch/finally
21 {
23 try {
26 }
15
ns.java 28
29
27
30 System.err.println(
Rethrow Exception
32 throw exception; // rethrow for further processing
33
Line 32
34 // any code here would not be reached
35 }
36
38 finally {
The finally block
executes, even though
39 System.err.println( "Finally executed in throwException" );
40 }
Exception thrown
41
Lines 38-40
42 // any code here would not be reached
43
45
48 {
50 try {
52 }
16
53
UsingExceptio
56 System.err.println( exception );
57 }
58
The finally
ns.java
60 finally {
61 System.err.println(
block always
62 "Finally executed in doesNotThrowException" );
63 }
executes
64
66
Lines 60-63
68
Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException
17
15.7 Stack Unwinding
18
Line 13 2
1 // Fig. 15.4: UsingExceptions.java
6 {
Line 19
8 try {
9 Call method
throwException();
throwExceptio
10
11
}
Line 24
16 }
17
20 {
21
Method declares a
// throw an exception and catch it in main
22 try {
23
throws clause
System.out.println( "Method throwException" );
25
Throw an
26
}
Exception
19
27 // catch is incorrect type, so Exception is not caught
29 System.err.println(
31 }
32
34 finally {
36 }
37
UsingExceptio
38 } // end method throwException
39
ns.java
Method throwException
Finally is always executed
Exception handled in main
20
15.8 printStackTrace,
getStackTrace and
getMessage
Throwable class
Method printStackTrace
Prints method call stack (helpful in debugging)
Method getStackTrace
Obtains stack-trace information
Method getMessage
Returns descriptive string
Uncaught exception – default exception handler –
displays complete stack trace
21
2
Line 8 1 // Fig. 15.5: UsingExceptions.java
6 {
7 try {
Lines 13-14
Call method1
8 method1(); // call method1
9 }
10
13
12
Print information
catch ( Exception exception ) {
14 generated by
exception.printStackTrace();
getMessage and
15
Lines 25-26
printStackTrace
16 // obtain the stack-trace information
18
20 System.out.println( "Class\t\tFile\t\t\tLine\tMethod" );
Print 21
22
StackTraceElements
// loop through traceElements to get exception description
22
27
28
Line 45
System.out.print( currentElement.getLineNumber() + "\t" );
29
31
32
Print
} // end catch
33
StackTraceElements
Line 49
34 } // end method main
35
37 method1 declares
public static void method1() throws Exception
a throw clause
38 {
Call method2
39 method2();
40 }
41
Line 51
42 // call method3; throw exceptions back to method1
43
method2 declares
public static void method2() throws Exception
a throw clause
44 {
45 method3();
Call method3
46 }
47
49
method3 declares
public static void method3() throws Exception
a throw clause
50 {
Throw an
52 }
Exception that
propagates back to
23 main
53
54 } // end class Using Exceptions
UsingExceptio
Stack trace from getStackTrace:
Class File Line Method
UsingExceptions UsingExceptions.java 51 method3
UsingExceptions UsingExceptions.java 45 method2
ns.java
UsingExceptions UsingExceptions.java 39 method1
UsingExceptions UsingExceptions.java 8 main
24
15.10 Declaring New
Exception Types
Extend existing exception class
25
15.11 Constructors and
Exception Handling
Constructor cannot return a value to indicate an error
Throw exception if constructor causes error
For example, if invalid initialization value given to
constructor and there is no sensible way to correct this
26