07 1 Exception Handling
07 1 Exception Handling
» Improves clarity
5
» Enhances modifiability
» ArithmeticException – can arise from a number
of different problems in arithmetic
Result: 100 / 7 = 14
Please enter an integer numerator: 100
Please enter an integer denominator: 7
Result: 100 / 7 = 14
» Stack trace
˃ Name of the exception in a descriptive message that
indicates the problem
˃ Complete method-call stack
InputMismatchException
thrown if input not valid integers
Call method quotient,
Catching InputMismatchException
which may throw
(user has entered non-integer input)
ArithmeticException
29 int result = quotient( numerator, denominator );
30 System.out.printf( "\nResult: %d / %d = %d\n", numerator, 12
If we have reached this point,
31 denominator, result ); input was valid and
32 continueLoop = false; // input successful; end looping
33 } // end try
denominator was non-
34 catch ( InputMismatchException inputMismatchException ) zero, so looping can stop
35 {
36 System.err.printf( "\nException: %s\n",
37 inputMismatchException ); Exception parameters
38 scanner.nextLine(); // discard input so user can try again
39 System.out.println(
40 Read invalid input but do nothing with it
"You must enter integers. Please try again.\n" );
41 } // end catch
42 catch ( ArithmeticException arithmeticException ) Notify user of error made
43 {
44 System.err.printf( "\nException: %s\n", arithmeticException );
45 System.out.println(
46 "Zero is an invalid denominator. Please try again.\n" );
47 } // end catch
48 } while ( continueLoop ); // end do...while Catching ArithmeticException
49 } // end main
50 } // end class DivideByZeroWithExceptionHandling
(user has entered zero for denominator)
12
Result: 100 / 7 = 14
Result: 100 / 7 = 14
Exception: java.util.InputMismatchException
You must enter integers. Please try again.
Result: 100 / 7 = 14
13
» try block – encloses code that might throw an
exception and the code that should not execute if an
exception occurs
finally
{
statements
resource-release statements
} // end finally
Fig. 2 | Position of the finally block after the last catch block in a try statement.
35
» If no exception occurs, catch blocks are skipped and
control proceeds to finally block.
» After the finally block executes control proceeds to
first statement after the finally block.
» If exception occurs in the try block, program skips
rest of the try block. First matching the catch block
executes and control proceeds to the finally block.
If exception occurs and there are no matching catch
blocks, control proceeds to the finally block. After
the finally block executes, the program passes the
exception to the next outer the try block.
» If catch block throws an exception, the finally
36
44
45 } // end method throwException
46
47 // demonstrate finally when no exception occurs
48 public static void doesNotThrowException()
49 {
50 try // try block does not throw an exception
51 {
52 System.out.println( "Method doesNotThrowException" );
53 } // end try
54 catch ( Exception exception ) // does not execute
55 {
56 System.err.println( exception );
57 } // end catch
58 finally // executes regardless of what occurs in try...catch
59 {
60 System.err.println(
61
finally block executes even
"Finally executed in doesNotThrowException" );
62 } // end finally though no exception is thrown
63
64 System.out.println( "End of method doesNotThrowException" );
65 } // end method doesNotThrowException
66 } // end class UsingExceptions
Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
46
Method throwException
Finally is always executed
Exception handled in main
49
» An exception that is not caught in an application
causes Java’s default exception handler to run. This
displays the name of the exception, a descriptive
message that indicates the problem that occurred and
a complete execution stack trace.
» Throwable method toString (inherited by all
Throwable subclasses) returns a string containing the
name of the exception’s class and a descriptive
message.
50
Never ignore an exception you catch. At least use
printStackTrace to output an error message. This
will inform users that a problem exists, so that they can
take appropriate actions.
51
» Chained exceptions enable an exception object to
maintain the complete stack-trace information when
an exception is thrown from a catch block
option
1 // Fig. 13.9: AssertTest.java
2 // Demonstrates the assert statement
3 import java.util.Scanner;
4
5 public class AssertTest
6 {
7 public static void main( String args[] )
8 {
9 Scanner input = new Scanner( System.in );
10
11 System.out.print( "Enter a number between 0 and 10: " );
12 int number = input.nextInt(); Message to be displayed with
13 assert statement AssertionError
14 // assert that the absolute value is >= 0
15 assert ( number >= 0 && number <= 10 ) : "bad number: " + number;
16
17 System.out.printf( "You entered %d\n", number );
18 } // end main
If number is less than 0 or greater than
19 } // end class AssertTest 10, AssertionError occurs
Enter a number between 0 and 10: 5
You entered 5