lecture12 Exceptions PartIII

advertisement
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
// Fig. 15.1: DivideByZeroTest.java
// An exception-handling example that checks for divide-by-zero.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DivideByZeroTest extends JFrame
implements ActionListener {
private JTextField inputField1, inputField2, outputField;
private int number1, number2, result;
// set up GUI
public DivideByZeroTest()
{
super( "Demonstrating Exceptions" );
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new GridLayout( 3, 2 ) );
// set up label and inputField1
container.add(
new JLabel( "Enter numerator ", SwingConstants.RIGHT ) );
inputField1 = new JTextField();
container.add( inputField1 );
Outline
DivideByZeroTes
t.java
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// set up label and inputField2; register listener
container.add( new JLabel( "Enter denominator and press Enter ",
SwingConstants.RIGHT ) );
inputField2 = new JTextField();
container.add( inputField2 );
inputField2.addActionListener( this );
Outline
DivideByZeroTes
t.java
Line 51
// set up label and outputField
container.add( new JLabel( "RESULT ", SwingConstants.RIGHT ) );
outputField = new JTextField();
container.add( outputField );
Lines 52-53
setSize( 425, 100 );
setVisible( true );
} // end DivideByZeroTest constructor
// process GUI events
public void actionPerformed( ActionEvent event )
{
outputField.setText( "" );
// clear outputField
// read two numbers and calculate quotient
try {
number1 = Integer.parseInt( inputField1.getText() );
number2 = Integer.parseInt( inputField2.getText() );
The try block
Read integers from
JTextFields
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
result = quotient( number1, number2 );
outputField.setText( String.valueOf( result ) );
}
// process improperly formatted input
catch ( NumberFormatException numberFormatException ) {
JOptionPane.showMessageDialog( this,
"You must enter two integers", "Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
}
// process attempts to divide by zero
catch ( ArithmeticException arithmeticException ) {
JOptionPane.showMessageDialog( this,
arithmeticException.toString(), "Arithmetic Exception",
JOptionPane.ERROR_MESSAGE );
}
Outline
Method quotient
attempts division
DivideByZeroTes
t.java
Catch
NumberFormatException
Line 55
Line 60
Line 67
Catch
ArithmeticException
Line 77
} // end method actionPerformed
// demonstrates throwing an exception when a divide-by-zero occurs
public int quotient( int numerator, int denominator )
throws ArithmeticException
{
return numerator / denominator;
}
Method quotient throws
ArithmeticException
81
82
83
84
85
86
87
88
public static void main( String args[] )
{
DivideByZeroTest application = new DivideByZeroTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class DivideByZeroTest
Outline
DivideByZeroTes
t.java
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
// Fig. 15.3: UsingExceptions.java
// Demonstration of the try-catch-finally exception handling mechanism.
public class UsingExceptions {
public static void main( String args[] )
{
try {
throwException(); // call method throwException
}
// catch Exceptions thrown by method throwException
catch ( Exception exception ) {
System.err.println( "Exception handled in main" );
}
doesNotThrowException();
}
// demonstrate try/catch/finally
public static void throwException() throws Exception
{
// throw an exception and immediately catch it
try {
System.out.println( "Method throwException" );
throw new Exception(); // generate exception
}
Outline
UsingExceptions
.java
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// catch exception thrown in try block
catch ( Exception exception ) {
System.err.println(
"Exception handled in method throwException" );
throw exception; // rethrow for further processing
// any code here would not be reached
Outline
UsingExceptions
Rethrow .java
Exception
Line 32
}
Lines 38-40
// this block executes regardless of what occurs in try/catch
The finally block executes,
finally {
System.err.println( "Finally executed in throwException" ); even though Exception thrown
}
// any code here would not be reached
} // end method throwException
// demonstrate finally when no exception occurs
public static void doesNotThrowException()
{
// try block does not throw an exception
try {
System.out.println( "Method doesNotThrowException" );
}
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// catch does not execute, because no exception thrown
catch ( Exception exception ) {
System.err.println( exception );
}
// this clause executes regardless of what occurs in try/catch
finally {
System.err.println(
"Finally executed in doesNotThrowException" );
}
System.out.println( "End of method doesNotThrowException" );
} // end method doesNotThrowException
} // end class UsingExceptions
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
Outline
UsingExceptions
.java
The finally block
Lines 60-63
always executes
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
// Fig. 15.4: UsingExceptions.java
// Demonstration of stack unwinding.
public class UsingExceptions {
public static void main( String args[] )
{
// call throwException to demonstrate stack unwinding
try {
throwException();
}
// catch exception thrown in throwException
catch ( Exception exception ) {
System.err.println( "Exception handled in main" );
}
}
Outline
UsingExceptions
.java
Line 9
Call method
throwException
Line 13
Catch Exception
from
Line 19
method throwExcetion
Line 24
// throwException throws exception that is not caught in this method
public static void throwException() throws Exception
{
Method declares a
// throw an exception and catch it in main
throws clause
try {
System.out.println( "Method throwException" );
throw new Exception();
// generate exception
Throw an Exception
}
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// catch is incorrect type, so Exception is not caught
catch ( RuntimeException runtimeException ) {
System.err.println(
"Exception handled in method throwException" );
}
// finally clause always executes
finally {
System.err.println( "Finally is always executed" );
}
} // end method throwException
} // end class UsingExceptions
Method throwException
Finally is always executed
Exception handled in main
Outline
UsingExceptions
.java
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
Outline
// Fig. 15.5: UsingExceptions.java
// Demonstrating getMessage and printStackTrace from class Exception.
public class UsingExceptions {
UsingExceptions
.java
public static void main( String args[] )
{
try {
method1(); // call method1
}
Line 8
Call method1
Lines 13-14
// catch Exceptions thrown from method1
catch ( Exception exception ) {
System.err.println( exception.getMessage() + "\n" );
exception.printStackTrace();
Print information generated
Lines 25-26
by getMessage
and
printStackTrace
// obtain the stack-trace information
StackTraceElement[] traceElements = exception.getStackTrace();
System.out.println( "\nStack trace from getStackTrace:" );
System.out.println( "Class\t\tFile\t\t\tLine\tMethod" );
Print StackTraceElements
// loop through traceElements to get exception description
for ( int i = 0; i < traceElements.length; i++ ) {
StackTraceElement currentElement = traceElements[ i ];
System.out.print( currentElement.getClassName() + "\t" );
System.out.print( currentElement.getFileName() + "\t" );
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
System.out.print( currentElement.getLineNumber() + "\t" );
System.out.print( currentElement.getMethodName() + "\n" );
} // end for statement
} // end catch
} // end method main
Outline
UsingExceptions
.java
Print StackTraceElements
Lines 27-28
// call method2; throw exceptions back to main
public static void method1() throws Exception
{
method2();
}
Line
37 a
method1
declares
throw clause
Line 39
Call method2
// call method3; throw exceptions back to method1
public static void method2() throws Exception
{
method3();
}
Line 43
method2 declares a
45
throwLine
clause
Call method3
Line 49
// throw Exception back to method2
public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
}
Line
51 a
method3
declares
throw clause
Throw an
Exception that
propagates back to
main
53
54
Outline
} // end class Using Exceptions
Exception thrown in method3
java.lang.Exception: Exception thrown in method3
at UsingExceptions.method3(UsingExceptions.java:51)
at UsingExceptions.method2(UsingExceptions.java:45)
at UsingExceptions.method1(UsingExceptions.java:39)
at UsingExceptions.main(UsingExceptions.java:8)
Stack trace from getStackTrace:
Class
File
UsingExceptions UsingExceptions.java
UsingExceptions UsingExceptions.java
UsingExceptions UsingExceptions.java
UsingExceptions UsingExceptions.java
Line
51
45
39
8
Method
method3
method2
method1
main
UsingExceptions
.java
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
Outline
// Fig. 15.6: UsingChainedExceptions.java
// Demonstrating chained exceptions.
public class UsingChainedExceptions {
UsingChainedExc
eptions.java
public static void main( String args[] )
{
try {
method1(); // call method1
}
// catch Exceptions thrown from method1
catch ( Exception exception ) {
exception.printStackTrace();
}
Line 8
Call method1
Lines 12-14
Catch Exception
and printLine
stack18trace
}
Line 21
// call method2; throw exceptions back to main
public static void method1() throws Exception
{
try {
method2(); // call method2
}
method1
declares
Line
26 a
throw clause
Call method2
An existing Exception
is chained to another
// catch Exception thrown from method2
catch ( Exception exception ) {
throw new Exception( "Exception thrown in method1", exception );
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Outline
}
}
// call method3; throw exceptions back to method1
public static void method2() throws Exception
{
try {
method3(); // call method3
}
UsingChainedExc
method2
declares a
throweptions.java
clause
Line 31
Call method3
LineException
34
An existing
is chained to another
Line 39
// catch Exception thrown from method3
catch ( Exception exception ) {
throw new Exception( "Exception thrown in method2", exception );
}
}
// throw Exception back to method2
public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
}
} // end class Using Exceptions
Line 46
Throw a new
Exception
java.lang.Exception: Exception thrown in method1
at UsingChainedExceptions.method1(UsingChainedExceptions.java:26)
at UsingChainedExceptions.main(UsingChainedExceptions.java:8)
Caused by: java.lang.Exception: Exception thrown in method2
at UsingChainedExceptions.method2(UsingChainedExceptions.java:39)
at UsingChainedExceptions.method1(UsingChainedExceptions.java:21)
... 1 more
Caused by: java.lang.Exception: Exception thrown in method3
at UsingChainedExceptions.method3(UsingChainedExceptions.java:46)
at UsingChainedExceptions.method2(UsingChainedExceptions.java:34)
... 2 more
Outline
UsingChainedExc
eptions.java
Download