SlideShare a Scribd company logo
Chapter 18Chapter 18
Exceptions &Exceptions &
AssertionsAssertions
Java I ITP 120Java I ITP 120
ITP 120 Java Programming I
2
Patrick Healy
Class #14 – Exception Handling
Chapter Objectives
Understand the concept of exception handling
Become familiar with exception types
Learn how to use the try-catch block to handle exceptions
Learn how to throw exceptions
Understand the finally block
Learn how to create and use custom exceptions
Look at the Sum of Digits (Exercise 5.2) program with exceptions
See handout for students
ITP 120 Java Programming I
3
Patrick Healy
Class #14 – Exception Handling
Categories of Errors
There are three categories or types of errors:
(1) Syntax errors
(2) Logic errors (sometimes called: semantic errors)
(3) Runtime errors
Syntax errors arise because the rules of the language have not
been followed. They are detected by the compiler.
Logic errors occur when a program doesn't perform the way it
was intended to.
Runtime errors occur while the program is running if the
environment detects an operation that is impossible to carry out.
Runtime Errors
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
}
}
If an exception occurs on this
line, the rest of the lines in the
method are skipped and the
program is terminated.
Terminated.
1
2
3
4
5
6
7
8
9
10
11
12
13
Catching Runtime Errors
import java.util.*;
public class HandleExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
// Display the result
System.out.println(
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" +
"Incorrect input: an integer is required)");
scanner.nextLine(); // discard input
}
} while (continueInput);
}
}
If an exception occurs on this line,
the rest of lines in the try block are
skipped and the control is
transferred to the catch 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
13
ITP 120 Java Programming I
6
Patrick Healy
Class #14 – Exception HandlingCatching Runtime Errors (Another
example)
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
try {
String input = JOptionPane.showInputDialog(null,
"Please enter an integer");
int number = Integer.parseInt(input);
// Display the result
JOptionPane.showMessageDialog(null,
"The number entered is " + number);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Incorrect input: an integer is required");
}
System.out.println("Execution continues ...");
System.exit(0);
}
}
If an exception occurs on this line, the rest
lines in the try clause are skipped and the
control is transferred to the catch clause.
After the exception is caught and
processed, the control is transferred to the
next statement after the try-catch block.
ITP 120 Java Programming I
7
Patrick Healy
Class #14 – Exception Handling
Exception Handling : Exceptions vs
Errors
An exception is an object that defines an unusual or erroneous
situation
An exception is thrown by a program or the run-time environment and
can be caught and handled if desired.
The DIFFERENCE between an ERROR and an EXCEPTION:
An error is similar to an exception except that an error generally
represents an unrecoverable situation and cannot be caught.
ITP 120 Java Programming I
8
Patrick Healy
Class #14 – Exception Handling
Exception Handling : Examples of
ProblemsExamples of situations that cause exceptions to be thrown:
(1) Attempting to divide by zero: x = 126.57 / 0.0
(2) An array index is out of bounds
(3) A specified file could not be found
(4) An I/O operation could not be completed normally
(5) An attempt was made to follow a null reference (to an object)
ITP 120 Java Programming I
9
Patrick Healy
Class #14 – Exception Handling
Exception Handling : Dealing with
Problems
A Java program can be designed to:
(1) Not handle the exception at all.
(2) Handle the exception where it occurs. OR:
(3) Handle the exception at another place in the program.
ITP 120 Java Programming I
10
Patrick Healy
Class #14 – Exception Handling
Exception Handling
Exception handling is generally used to handle abnormal events in a
program.
When a method encounters a problem that disrupts the normal flow, it
can cause the program to CRASH !
But with exception handling, the method can throw an exception which
informs the caller that a problem occurred allowing the caller to
perform alternative actions.
Exception handling enables more robust programming by providing
ways of recovering from errors or problems.
ITP 120 Java Programming I
11
Patrick Healy
Class #14 – Exception Handling
Exceptions 2 types: Checked vs
Unchecked
Exception handling streamlines error handling by allowing your
program to define a block of code, called an exception handler that is
executed automatically when an error occurs.
Java defines standard exceptions for common errors such as divide-
by-zero and file-not-found. (these are Unchecked exceptions and
beyond the control of the programmer)
Checked exceptions CAN be handled in Java programs.
To respond to these errors, your program must watch for and handle
these exceptions.
ITP 120 Java Programming I
12
Patrick Healy
Class #14 – Exception Handling
Exceptions and Exception Types
ITP 120 Java Programming I
13
Patrick Healy
Class #14 – Exception HandlingSystem Errors (Note: click the mouse to see
fly-ins)
System errors are thrown by
JVM and represented in the
Error class. The Error class
describes internal system
errors. Such errors rarely
occur. If one does, there is
little you can do beyond
notifying the user and
trying to terminate the
program gracefully.
ITP 120 Java Programming I
14
Patrick Healy
Class #14 – Exception HandlingExceptions (Note: click the mouse to see
fly-ins)
Exceptions are represented
in the Exception class that
describes errors caused by
your program and external
circumstances. These
errors can be caught and
handled by your program.
ITP 120 Java Programming I
15
Patrick Healy
Class #14 – Exception HandlingRuntime Exceptions (Note: click the mouse to see
fly-ins)
Runtime exceptions are
represented in the
RuntimeException class that
describes programming
errors, such as bad casting,
accessing an out-of-bounds
array, and numeric errors.
ITP 120 Java Programming I
16
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in UnChecked Exceptions
Exception Meaning
ArithmeticException Arithmetic error; divide-by-zero
ArrayIndexOutOfBoundsException Array index is out of bounds
ArrayStoreException Assignment of an array element
is an incompatible type.
ClassCastException Invalid cast operation
IllegalArgumentException Illegal argument used to invoke a
method
IndexOutOfBoundsException Some type of index is out of
bounds
ITP 120 Java Programming I
17
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in UnChecked Exceptions
Exception Meaning
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a
numeric format
StringIndexOutOfBounds Attempt to index outside the bounds of a
string
ITP 120 Java Programming I
18
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in Checked Exceptions
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that
does not implement the Cloneable
interface
IllegalAccessException Access to a class is denied
Instantiation Exception Attempt to create an object of an
abstract class or interface.
InterruptedException One thread has been interrupted by
another thread
NoSuchMethodException Method does not exist
Checked vs. Unchecked
Exceptions
RuntimeException, Error and their subclasses are
known as UNCHECKED EXCEPTIONS.
All other exceptions are known as CHECKED
EXCEPTIONS, meaning that the compiler forces
the programmer to check and deal with the
exceptions.
Unchecked Exceptions
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable. For example, a
NullPointerException is thrown if you access an object
through a reference variable before an object is assigned to
it; an IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array.
These are the logic errors that should be corrected in the
program. Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-catch blocks,
Java does not mandate you to write code to catch unchecked
exceptions.
Declaring Exceptions
Every method should state the types of checked
exceptions it might throw. This is known as
declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate exception
type and throw it. This is known as throwing an
exception. Here is an example,
throw new SomeException();
SomeException ex = new SomeException();
throw ex;
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentExceptionthrows IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Catching Exceptions
main method {
...
try {
...
invoke method1;
statement1;
}
catch (Exception1 ex1) {
Process ex1;
}
statement2;
}
method1 {
...
try {
...
invoke method2;
statement3;
}
catch (Exception2 ex2) {
Process ex2;
}
statement4;
}
method2 {
...
try {
...
invoke method3;
statement5;
}
catch (Exception3 ex3) {
Process ex3;
}
statement6;
}
An exception
is thrown in
method3
ITP 120 Java Programming I
26
Patrick Healy
Class #14 – Exception Handling
Catching Exceptions
Consider the scenario on the previous graphic slide:
Suppose an exception occurs in the try-catch block that contains a call to
method3.
If the exception type is Exception3, it is caught by the catch clause for
handling ex3 in Method 2
If the exception type is Exception2, it is caught by the catch clause for
handling ex2 in Method 1
If the exception type is Exception1, it is caught by the catch clause for
handling ex1 in the main method.
If the exception type is NOT Exception1, Exception2, or Exception3, the
program terminates.
ITP 120 Java Programming I
27
Patrick Healy
Class #14 – Exception Handling
Catching Exceptions: Previous slide
Still referring to the scenario on the previous graphic slide:
If the exception type is Exception3, then statement 5 is skipped.
If the exception type is Exception2, then statements 3 & 5 are
skipped.
If the exception type is Exception1, then statements 1,3 & 5 are skipped.
ITP 120 Java Programming I
28
Patrick Healy
Class #14 – Exception Handling
Catching Exceptions in Graphics
Programs
Note:
An exception is ignored when …
an exception of a subclass of class Exception occurs in a graphics
program, Java prints the error message on the monitor, but the program
goes back to its GUI processing loop to run continuously.
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or RuntimeException),
you must invoke it in a try-catch block or declare to throw the exception in
the calling method. For example, suppose that method p1 invokes method p2
and p2 may throw a checked exception (e.g., IOException), you have to write
the code as shown in figure (a) OR figure (b).
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a) (b)
void p1() throws IOException {
p2();
}
Trace a Program Execution
animation
try {
statements;
}
catch(TheException
ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose no
exceptions in the
statements
Trace a Program Execution
animation
try {
statements;
}
catch(TheException
ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block is
always executed
Trace Execution
animation
try {
statements;
}
catch(TheException
ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Next statement in
the method is
executed
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Suppose an exception
of type Exception1 is
thrown in statement2
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The exception is
handled here
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The final block
statements are always
executed.
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
The next statement in
the method in the
program is now
executed.
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
statement2 throws an
exception of type
Exception2.
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Handle the exception
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Execute the finally
block statements
Trace a Program Execution
animation
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Rethrow the exception
and control is
transferred to the
calling statement in the
method
ITP 120 Java Programming I
41
Patrick Healy
Class #14 – Exception Handling
Claiming & Throwing Exceptions
Claiming an Exception (“throws”)
Every method must state the types of exceptions it can encounter.
The term claiming an exception tells the compiler what can go wrong.
public void someMethod( ) throws IOException
Throwing an Exception (“throw”)
When a program statement causes an error, the method containing he
statement creates an exception object and passes it on to the system.
The exception object contains information about the exception
including the exception type and the state of the program when the
error occurred.
The Java code that handles the error is the exception handler.
ITP 120 Java Programming I
42
Patrick Healy
Class #14 – Exception Handling
GUI Calculator Code Fragment
public void calculator(int operator){
//Using try -catch block for improperly formatted input.
try {
double num1 = new Double(jtfNumber1.getText().trim()).doubleValue();
double num2 = new Double(jtfNumber2.getText().trim()).doubleValue();
double result = 0.0;
switch (operator) {
case 0 : result = (num1 + num2); break;
case 1 : result = (num1 - num2); break;
case 2 : result = (num1 * num2); break;
case 3 : result = (num1 * 1.0 / num2); break;
}
String str = String.format("%1.4f", result);
jtfResult.setText(String.valueOf(str));
// Process improperly formatted input.
}
catch (NumberFormatException numberError){
JOptionPane.showMessageDialog(this,
"You must enter two values", "Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
clearFields();
}
}//End of calculate-method.
ITP 120 Java Programming I
43
Patrick Healy
Class #14 – Exception Handling
The JVM handles a Divide Exception !
// ExcDemoInfinity.java
import javax.swing.JOptionPane;
public class ExcDemoInfinity {
public static void main(String args[]) {
double result;
String output = "";
result = 1234.56 / 0.0; // Try to divide by zero
try {
System.out.println( result ); // Just the word "Infinity" is printed
}
catch (Exception ex)
{
System.out.println("Exception message is never printed" + ex.getMessage());
}
System.out.println("End of program");
output = "The word "Infinity" is printed" + "n" + "Exception was handled by the JVM";
JOptionPane.showMessageDialog(null,output);
} // End of main method
} // End of class ExcDemoInfinity
ITP 120 Java Programming I
44
Patrick Healy
Class #14 – Exception Handling
Claiming & Throwing Exceptions
Catching an Exception
This is the process of finding an exception handler.
The exception handler must match the type of exception thrown.
( see demo program ExcTypeMismatch.java )
If no matching handler is found, the program terminates.
ITP 120 Java Programming I
45
Patrick Healy
Class #14 – Exception Handling
Claiming & Throwing Exceptions: throws &
throw
Use the keyword throws to claim an exception.
Example:
public void myDivideMethod ( double d1, double d2 )
throws RunTimeException
Use the keyword throw to throw an exception
Example:
if( checkAmount > availableBalance) throw new
InsufficientFundsException( );
ITP 120 Java Programming I
46
Patrick Healy
Class #14 – Exception Handling
Throwing Exceptions
In the method that has claimed the exception, you can throw an object
of the exception if the exception arises.
The following is the syntax to throw an exception:
throw new MyException ( );
Or:
MyException myEx = new MyException ( );
throw myEx;
ITP 120 Java Programming I
47
Patrick Healy
Class #14 – Exception Handling
Catching, Claiming, and Throwing
Exceptions
method1()
{
try
{
invoke method2;
}
catch (Exception ex)
{
Process exception;
}
}
method2() throws Exception
{
if (an error occurs)
{
throw new Exception();
}
}
catch exception throw exception
claim exception
ITP 120 Java Programming I
48
Patrick Healy
Class #14 – Exception Handling
Some Constructors & Methods
of class Throwable
public Throwable ( )
Default constructor
Creates an instance of Throwable with an empty message string
public Throwable (String messageString)
Constructor with parameters
Creates an instance of Throwable with the message string specified
by the parameter messageString
ITP 120 Java Programming I
49
Patrick Healy
Class #14 – Exception Handling
Some Constructors & Methods of class
Throwable
public String getMessage( )
Returns the detailed message stored in the object
public void printStackTrace( )
Method to print the stack trace showing the sequence of method calls
when an exception occurs
ITP 120 Java Programming I
50
Patrick Healy
Class #14 – Exception Handling
Some Constructors & Methods of class
Throwable
public void printStackTrace(PrintWriter stream )
Method to print the stack trace showing the sequence of method calls
when an exception occurs. Output is sent to the stream specified by
parameter stream.
public String toString( )
Returns a string representation of the Throwable object
ITP 120 Java Programming I
51
Patrick Healy
Class #14 – Exception Handling
The Exception Hierarchy
In Java, all exceptions are represented in the various classes.
All exception classes are derived from a class called Throwable
The two direct subclasses of the class Throwable are:
Exception and Error
Exceptions of type Error are related to errors that occur in the Java
Virtual Machine (JVM) itself and NOT in your program.
Error type exceptions are BEYOND YOUR CONTROL !
Exceptions of type Exception are errors that result from YOUR
program’s activity.
RunTimeException is an important subclass of subclass Exception.
ITP 120 Java Programming I
52
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in Exceptions
Inside the java.lang package, Java defines several exception classes.
The most general of these exceptions are subclasses of the standard
type RuntimeException.
Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.
The unchecked exceptions defined in java.lang are listed on
subsequent slides in this presentation.
Unchecked exceptions are exceptions that the compiler does NOT
check to see if a method handles or throws those exceptions.
Checked exceptions MUST be caught and handled.
ITP 120 Java Programming I
53
Patrick Healy
Class #14 – Exception Handling
2 Types of Exceptions: Checked &
Unchecked

UNCHECKED EXCEPTIONS: (NOT checked by the compiler)
Do NOT have to be caught. (Beyond your control)

CHECKED EXCEPTIONS: (Checked by the compiler)
They MUST be caught and handled.
ITP 120 Java Programming I
54
Patrick Healy
Class #14 – Exception Handling
About Checked & Unchecked Exceptions…
Checked Exceptions (Checked by the Java compiler)
Any exception that can be analyzed by the compiler is called a
checked exception. For example, IOExceptions are checked exceptions.
Since the methods read and readLine throw IOException, these methods
throw checked exceptions. When the compiler encounters these method
calls, it checks whether the program handles IOException, or reports
them by throwing them.
Having the compiler check for exceptions reduces the number of
exceptions not properly handled by the program.
ITP 120 Java Programming I
55
Patrick Healy
Class #14 – Exception Handling
About Checked & Unchecked Exceptions…
Unchecked exceptions are those NOT checked by the Java compiler.
When a program is being compiled, it may NOT be possible for the
compiler to determine if exceptions such as division-by-zero or array-
index-out-of-bounds will occur.
Therefore, to improve the reliability and correctness of Java programs,
programmers should check for these types of exceptions.
ITP 120 Java Programming I
56
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in UnChecked Exceptions
Exception Meaning
ArithmeticException Arithmetic error; divide-by-zero
ArrayIndexOutOfBoundsException Array index is out of bounds
ArrayStoreException Assignment of an array element
is an incompatible type.
ClassCastException Invalid cast operation
IllegalArgumentException Illegal argument used to invoke a
method
IndexOutOfBoundsException Some type of index is out of
bounds
ITP 120 Java Programming I
57
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in UnChecked Exceptions
Exception Meaning
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a
numeric format
StringIndexOutOfBounds Attempt to index outside the bounds of a
string
Exceptions in GUI Applications
The methods are executed on the threads. If an exception occurs
on a thread, the thread is terminated if the exception is not
handled. However, the other threads in the application are not
affected. There are several threads running to support a GUI
application. A thread is launched to execute an event handler
(e.g., the actionPerformed method for the ActionEvent). If an
exception occurs during the execution of a GUI event handler,
the thread is terminated if the exception is not handled.
Interestingly, Java prints the error message on the console, but
does not terminate the application. The program goes back to its
user-interface-processing loop to run continuously.
Example: Exceptions in GUIs
An error message appears on the console,
but the GUI application continues running.
Write a program that creates a user
interface to perform integer divisions. The
user enters two numbers in the text fields
Number 1 and Number 2. The division of
Number 1 and Number 2 is displayed in the
Result field when the Divide button is
clicked.
ITP 120 Java Programming I
60
Patrick Healy
Class #14 – Exception Handling
Exceptions thrown by methods of class
Integer
Remember: Java programs accept only STRINGS as input.
Numbers, integer or decimal, are entered as strings !
The method parseInt of the class Integer is used to convert an integer
string into the equivalent integer. If the string contains any character
that is not a number, the method parseInt will throw an exception:
NumberFormatException (an unchecked exception)
Also, the method parseDouble will throw an exception if the string does
not contain a valid number.
double dblNumber = Double.parseDouble (inputString);
ITP 120 Java Programming I
61
Patrick Healy
Class #14 – Exception Handling
Java’s Built-in Checked Exceptions
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that
does not implement the Cloneable
interface
IllegalAccessException Access to a class is denied
Instantiation Exception Attempt to create an object of an
abstract class or interface.
InterruptedException One thread has been interrupted by
another thread
NoSuchMethodException Method does not exist
ITP 120 Java Programming I
62
Patrick Healy
Class #14 – Exception Handling
Exception Handling Fundamentals
Java exception handling is managed using five keywords:
try, catch, throw, throws, finally
Program statements that you want to monitor are contained within a try
block. If an exception occurs within the try block, it is thrown.
Your program code can catch this exception using a catch statement
and handle it in some rational manner.
To manually throw an exception, use the keyword throw.
Any code that absolutely must be executed upon exiting from a try
block is put in a finally block.
ITP 120 Java Programming I
63
Patrick Healy
Class #14 – Exception Handling
Exception Handling Fundamentals
To manually throw an exception, use the keyword throw.
public void setRadius ( double newRadius)
throws IllegalArgumentException
{
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
“ THE CIRCLE’S RADIUS CANNOT BE NEGATIVE !");
}
Any code that absolutely must be executed upon exiting from a try block is put in a
finally block. (see next slide )
ITP 120 Java Programming I
64
Patrick Healy
Class #14 – Exception Handling
Handling Exceptions within a Program
The general syntax of the try/catch/finally block is:
try
{
// statements that may throw exceptions
}
catch (ExceptionClassName1 ex1)
{
// exception handler code statements
}
continued on next page 
ITP 120 Java Programming I
65
Patrick Healy
Class #14 – Exception Handling
Handling Exceptions within a Program
(cont.)
catch (ExceptionClassName2 ex2)
{ // exception handler code }
…
catch (ExceptionClassName3 ex3)
{ // exception handler code }
finally // The finally block is always executed !
{ // finally block statements }
ITP 120 Java Programming I
66
Patrick Healy
Class #14 – Exception Handling
Handling Exceptions within a Program
(cont.)
Consider the following catch block:
catch ( ArithmeticException ex )
{
System.out.println(“Error: “ + ex.getMessage( ) );
}
The catch block catches an exception of type ArithmeticException
which is a runtime exception. The identifier ex is an identifier is a
reference variable of the type ArithmeticException.
ITP 120 Java Programming I
67
Patrick Healy
Class #14 – Exception Handling
Handling Exceptions within a Program
(cont.)
If an ArithmeticException is thrown by the associated try block, the
reference parameter ex contains the address of the exception thrown
by the try block.
The object ex stores a detailed description of the the thrown
exception.
The method getMessage( ) or the method toString( ) will retrieve and
print the message containing the description of the thrown exception.
ITP 120 Java Programming I
68
Patrick Healy
Class #14 – Exception Handling
Handling Exceptions within a Program
(cont.)Examples:
catch ( ArithmeticException ex )
{ // Below: Use either getMessage( ) or toString( )
System.out.println(“Error: “ + ex.getMessage( ) );
System.out.println(“Error: “ + ex.toString( ) );
}
catch ( NumberFormatException numEx )
{
System.out.println(“Error: “ + numEx.getMessage( ) );
}
ITP 120 Java Programming I
69
Patrick Healy
Class #14 – Exception Handling
Exception Handling
Example 18.1 This program aborts due to an attempt to divide by zero
public class TestException1
{
public static void main( String[ ] args )
{
System.out.println ( 120.5 / 0); // Division by zero
} // End main method
} // End of class TestException1
ITP 120 Java Programming I
70
Patrick Healy
Class #14 – Exception Handling
Exception Handling
Example 18.2 This program handles the divide by zero error when it occurs
public class TestException2 {
public static void main( String[ ] args ) {
try
{
System.out.println( 120 / 0 ); // Divide by zero attempted
}
catch( Exception ex ) // Exception is a class; ex is an object of
// class Exception
{
System.out.println(“Error: “ + ex.getMessage());
}
System.out.println(“Continued execution after handling the error” );
} // End main method
} // End of class TestException2
ITP 120 Java Programming I
71
Patrick Healy
Class #14 – Exception Handling
Exception Handling
Exceptions are thrown by methods
But … not all methods throw exceptions
If a method throws exceptions, it is the responsibility of the caller to
handle the problems reported by the method.
Generally, methods throw exceptions to report problems or
any events (other than the expected one) to the caller of the method
ITP 120 Java Programming I
72
Patrick Healy
Class #14 – Exception Handling
Exceptions and Exception Types
There is a hierarchy of exceptions with Throwable being at the top
Two types of exceptions: Checked Exceptions and Unchecked
Exceptions.
Checked Exceptions are exceptions that must be caught
Unchecked Exceptions do NOT have to be caught
Examples of unchecked exceptions:
RuntimeException and its subclasses such as:
ArithmeticException,
IndexOutOfBoundsException,
NullPointerException
ITP 120 Java Programming I
73
Patrick Healy
Class #14 – Exception Handling
Claiming an Exception
Java’s Exception handling is based on three operations
Claiming an exception
Throwing an exception
Catching an exception
Claiming an exception
By using the keyword throws in a method declaration to inform the
compiler that the method might throw an exception
Example:
public void Amethod() throws IOException
A method also lets any caller know to expect IOException may be
thrown
A method may throw more than one exception. It must include all of
them in the declaration, each separated by comma
public void Bmethod() throws Exception1, Exception2, Exception3
ITP 120 Java Programming I
74
Patrick Healy
Class #14 – Exception Handling
Throwing an Exception
After a method declares that it might throw an exception, it is free to
throw it from inside the method.
public void Amethod( ) throws IOException
{
// Doing some operations and something goes wrong
throw new IOException();
}
A method can throw more than one exception since any number of
things can go wrong.
ITP 120 Java Programming I
75
Patrick Healy
Class #14 – Exception Handling
Catching an Exception
The caller of a method which throws an exception must be prepared to catch the
exception by using the try-catch block.
try
{
Bmethod( ); // Bmethod might throw any of the exceptions caught below:
}
catch(Exception1 ex1)
{
// Handle the problem here
}
catch(Exception2 ex2)
{
// handle the problem here
}
catch(Exception3 ex3)
{
// Handle the problem here
}
ITP 120 Java Programming I
76
Patrick Healy
Class #14 – Exception Handling
Exception Handling
Example 18.3
public class Divide
{
private double number1;
private double number2;
Divide( ) { // Default constructor
number1 = 1;
number2 = 2; }
Divide( double num1, double num2) //Constructor with parameters
{ number1 = num1;
number2 = num2; }
public double divideMethod( ) throws ArithmeticException
{
if ( number2 == 0 )
throw new ArithmeticException(“The denominator is zero ‘);
else
return number1 / number2; // It is safe to carry out the division.
}
}
ITP 120 Java Programming I
77
Patrick Healy
Class #14 – Exception Handling
Example 18.3 continued
public class TestDivide
{
public static void main( String[ ] args)
{
Divide myDivider = new Divide( 5, 3); // Create new object
try
{
System.out.println(myDivider.divideMethod());
}
catch(ArithmeticException ex)
{
System.out.println (“Error: “ + ex.getMessage() );
}
}
}
ITP 120 Java Programming I
78
Patrick Healy
Class #14 – Exception Handling
Example 18.3 continued
public class TestDivide
{ // If the first statement in a “try” block causes an exception,
// the next statement will NOT be executed.
public static void main( String[ ] args)
{
Divide myDivider = new Divide( 21,0); // Instantiate 1st
object
Divide myDivider2 = new Divide (16, 4); // Instantiate 2nd
object
try
{
System.out.println(myDivider.divideMethod( )); // Causes divide exception
System.out.println(myDivider2.divideMethod( )); // Won’t be executed !
}
catch(ArithmeticException ex)
{
System.out.println (“Error: “ + ex.getMessage() );
}
}
}
ITP 120 Java Programming I
79
Patrick Healy
Class #14 – Exception Handling
Using try and catch
Keywords try and catch work together; you cannot have a try without a
catch or a catch without a try. The general form of the try/catch
exception follows:
try {
// (Block of code to monitor for errors)
}
catch (ExceptionType1 exOb) {
// Handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// Handler for ExceptionType2
}
ITP 120 Java Programming I
80
Patrick Healy
Class #14 – Exception Handling
Using try and catch
As the previous general form example shows, there can be more than
one catch statement associated with a try.
The type of exception determines which catch statement is executed.
Only that catch statement is executed; all others are by-passed.
When an exception is caught, exOb will receive its value.
If NO exception is thrown, then the try block ends normally, and all of
the catch statements are bypassed.
Execution then resumes with the first statement following the
last catch statement
Catch statements are executed only if an exception is thrown.
ITP 120 Java Programming I
81
Patrick Healy
Class #14 – Exception Handling
A Simple Exception Example
class ExcDemo1 { // Demonstrate exception handling
public static void main(String[ ] args) {
int nums[ ] = new int[4]; // One-dimensional array of 4 integer numbers
try {
System.out.println("Before exception is generated.");
// Generate an index out-of-bounds exception.
nums[7] = 25; // Attempt to store the integer 25 into 8th
array position
System.out.println("this won't be displayed"); }
catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(“Error from Java: “ + ex.getMessage( ) );
System.out.println("Index out-of-bounds!");
} // End of catch statement
System.out.println("After catch statement.");
} // End of main method
} // End of class ExcDemo1
ITP 120 Java Programming I
82
Patrick Healy
Class #14 – Exception Handling
A Simple Exception example (continued)
Output from running Java program ExcDemo1
Before exception is generated.
Error from Java: null
Index out-of-bounds!
After catch statement.
ITP 120 Java Programming I
83
Patrick Healy
Class #14 – Exception Handling
Another Exception Example:
// An exception can be generated by one method and caught by another.
public class ExcTest { // See next slide 
// Generate an exception.
static void genException() // The offending method
{ int nums[ ] = new int[4]; // Declare an array of integers
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 120; // Attempt to store 120 into the 8th
array member
System.out.println(“This message won't be displayed !"); }
} // End of class ExcTest
An
ITP 120 Java Programming I
84
Patrick Healy
Class #14 – Exception Handling
Another Exception Example (continued)
class ExcDemo2 {
public static void main(String[ ] args) {
try {
ExcTest . genException ( ); // Use class ExcTest (see previous slide)
}
catch (ArrayIndexOutOfBoundsException ex) {
// catch the exception
System.out.println(“Exception: “ + ex.getMessage( ) );
System.out.println("Index out-of-bounds!"); // This is printed
}
System.out.println("After catch statement."); // This is printed
} // End of main method
} // End of class ExcDemo2
ITP 120 Java Programming I
85
Patrick Healy
Class #14 – Exception Handling
The Consequences of an Uncaught
Exception
Catching one of Java’s standard exceptions has a benefit…
It prevents abnormal program termination.
If your program does NOT catch an exception, then it will be caught by
the Java Virtual machine (JVM).
But… the JVM’s default exception handler terminates execution and
displays a stack trace and error message.
In the next example, the index-out-of-bounds exception is NOT caught
by the program.
ITP 120 Java Programming I
86
Patrick Healy
Class #14 – Exception Handling
The Consequences of an Uncaught
Exception
// Let JVM handle the error.
class NotHandled {
public static void main(String[ ] args) {
int nums[ ] = new int[4];
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 54; // Try to assign a number to the 8th
position
} // End of main method
} // End of class NotHandled
ITP 120 Java Programming I
87
Patrick Healy
Class #14 – Exception Handling
The Consequences of an Uncaught
Exception
In the previous program, when the array index error occurs, execution
is halted, and the following error message is displayed:
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException
at NotHandled.main (NotHandled.java:9)
ITP 120 Java Programming I
88
Patrick Healy
Class #14 – Exception Handling
Exception Type must match Type in the
catch
The type of exception MUST match the type specified in a catch
statement. If there is a mismatch, there will be an abnormal program
termination.
In the next example, the program tries to catch an array boundary error
with a catch statement for an ArithmeticException (another of Java’s
built-in exceptions) When the array boundary is overrun, an
ArrayIndexOutOfBoundsException is generated, but it won’t be caught
by the catch statement.
Run the Java program ExcTypeMismatch.java to verify.
ITP 120 Java Programming I
89
Patrick Healy
Class #14 – Exception Handling
Exception Type must match Type in the
catch
Exception Type must match the type in the catch
// This won't work!
class ExcTypeMismatch {
public static void main(String[ ] args) {
int [ ] nums = new int[4];
try {
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 55; // Attempt to store 55 into 8th
array position
System.out.println(“This won't be displayed");
}
ITP 120 Java Programming I
90
Patrick Healy
Class #14 – Exception Handling
Exception Type must match Type in the
catch
// Can't catch an array boundary error with an ArithmeticException.
catch (ArithmeticException exc) // Incorrect exception type
{
// catch the exception
System.out.println("Index out-of-bounds!"); // Incorrect message!
}
System.out.println("After catch statement."); // Not printed
} // End of main method
} // End of class
ITP 120 Java Programming I
91
Patrick Healy
Class #14 – Exception Handling
Exceptions Help You to Handle Errors
Gracefullypublic class ExcDemo3 { // Handle errors gracefully & continue
public static void main(String[ ] args) {
int number[ ] = { 4, 8, 16, 32, 64, 128 };
int denom[ ] = { 2, 0, 4, 4, 0, 8 };
for(int i=0; I <number.length; i++) {
try {
System.out.println(number[i] + " / " + denom[i] + " is " + number[i] / denom[i]); }
catch (ArithmeticException ex) {
// catch the exception
System.out.println("Can't divide by Zero!"); }
} // End of for loop
} // End of main
} // End of class ExcDemo3
ITP 120 Java Programming I
92
Patrick Healy
Class #14 – Exception Handling
Using Multiple Catch Statements
You can associate more than one catch statement with a try.
This is commonly done.
However, each catch statement must catch a different type of
exception.
In the next example, the program catches two types of errors:
array boundary errors
divide-by-zero errors.
ITP 120 Java Programming I
93
Patrick Healy
Class #14 – Exception Handling
Using Multiple Catch Statements
// Use multiple catch statements.
class ExcDemo4 {
public static void main(String[ ] args) {
// Here, array number is longer than array denom.
int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; // 8 elements
int denom[ ] = { 2, 0, 4, 4, 0, 8 }; // 6 elements
for(int i=0; i<number.length; i++) {
try {
System.out.println(number[i] + " / " + denom[i] + " is " +
number[i]/denom[i]);
}
ITP 120 Java Programming I
94
Patrick Healy
Class #14 – Exception Handling
Using Multiple Catch Statements
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Cannot divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException ex) {
// catch the exception
System.out.println(“Exception: “ + ex.getMessage( ));
System.out.println("No matching element found."); }
} // End of for loop
} // End of main
} // End of class ExcDemo4
ITP 120 Java Programming I
95
Patrick Healy
Class #14 – Exception Handling
Using Multiple Catch Statements
The output of the previous program ExcDemo4 is:
4 / 2 is 2
Can’t divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can’t divide by Zero!
128 / 8 is 16
No matching element found.
No matching element found.
ITP 120 Java Programming I
96
Patrick Healy
Class #14 – Exception Handling
Catching SubClass Exceptions
A catch clause for a superclass will also match any of its subclasses.
For example, since the superclass of all exceptions is Throwable, to
catch all possible exceptions, just catch Throwable !
If you want to catch exceptions of both a superclass type and a
subclass type, put the subclass first in the catch sequence.
Putting the superclass first causes unreachable code to be created
since the subclass catch clause can never execute the code.
In Java, unreachable code is an error !
ITP 120 Java Programming I
97
Patrick Healy
Class #14 – Exception Handling
Catching SubClass Exceptions
// Subclasses must precede superclasses in catch statements.
class ExcDemo5 {
public static void main(String[ ] args) {
// Here, array number is longer than array denom.
int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 };
int denom[ ] = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<number.length; i++) {
try {
System.out.println(number[i] + " / " + denom[i] + " is " +
number[i] / denom[i]);
}
ITP 120 Java Programming I
98
Patrick Healy
Class #14 – Exception Handling
Catching SubClass Exceptions
catch (ArrayIndexOutOfBoundsException exc) // Subclass is first !
{
System.out.println("No matching element found.");
}
catch (Throwable ex) // From superclass Throwable
{
System.out.println("Some type of exception occurred !");
// Could also add: System.out.println(“Exception: “ + ex.getMessage( ) + “ occurred”);
}
} // End of for loop
} // End of main method
} // End of class ExcDemo5
ITP 120 Java Programming I
99
Patrick Healy
Class #14 – Exception Handling
Catching SubClass Exceptions
Output from the program ExcDemo5:
4 / 2 is 2
Some exception occurred.
16 / 4 is 4
32 / 4 is 8
Some exception occurred.
128 / 8 is 16
No matching element found.
No matching element found.
ITP 120 Java Programming I
100
Patrick Healy
Class #14 – Exception Handling
Try Blocks can be Nested
One try block can be nested within another. An exception generated
within the inner try block that is NOT caught by a catch associated with
that inner try is propagated to the outer try block.
In the next program example, the ArrayIndexOutOfBoundsException is
NOT caught by the inner try block, but it is caught by the outer try
block.
ITP 120 Java Programming I
101
Patrick Healy
Class #14 – Exception Handling
Try Blocks can be Nested
// Use a nested try block. Catch error in outer block
class NestTrys {
public static void main(String[ ] args) {
// Here, number array is longer than denom array
int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; // 8 elements
int denom[ ] = { 2, 0, 4, 4, 0, 8 }; // 6 elements
try { // outer try
for(int i=0; I < number.length; i++) {
try { // nested try Start of inner try block
System.out.println(number[i] + " / " + denom[i] + " is " +
number[i] / denom[i]);
} // End of inner try
ITP 120 Java Programming I
102
Patrick Healy
Class #14 – Exception Handling
Try Blocks can be Nested
catch (ArithmeticException ex) {
System.out.println("Can't divide by Zero!"); // Catch the exception
}
} // End of for loop
} // End of outer try
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
System.out.println("Fatal error -- program terminated.");
}
} // End of main method
} // End of class NestTrys
ITP 120 Java Programming I
103
Patrick Healy
Class #14 – Exception Handling
Try Blocks can be Nested
In the previous program example, an exception that can be handled by the inner try, a
divide-by-zero error, allows the program to continue.
However, an array boundary error is caught by the outer try which causes the
program to terminate.
Output from the previous program example is:
4 / 2 is 2
Can’t divide by Zero!
16 / 4 is 4
32 / 4 is 8
Can’t divide by Zero!
128 / 8 is 16
No matching element found.
Fatal error – program terminated. < --------- Note
ITP 120 Java Programming I
104
Patrick Healy
Class #14 – Exception Handling
Throwing an Exception Manually
The previous examples have been catching exceptions generated
automatically by the Java Virtual Machine (JVM)
However, it is possible to manually throw an exception by using the
throw statement. The general form of the throw statement is:
throw exceptOb;
exceptOb must be an object of class Exception which is derived from
class Throwable (which is derived from class Object)
ITP 120 Java Programming I
105
Patrick Healy
Class #14 – Exception Handling
Throwing an Exception Manually
// Manually throw an exception.
class ThrowDemo {
public static void main(String[ ] args) {
try {
System.out.println("Before throw.");
throw new ArithmeticException( );
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Exception caught.");
}
System.out.println("After try/catch block.");
} // End of main method
} // End of class ThrowDemo
ITP 120 Java Programming I
106
Patrick Healy
Class #14 – Exception Handling
Throwing an Exception Manually
Output from the previous program ThrowDemo:
Before throw.
Exception caught.
After try/catch block.
ITP 120 Java Programming I
107
Patrick Healy
Class #14 – Exception Handling
Rethrowing an Exception
An exception caught by one catch statement can be rethrown so that it
can be caught by an outer catch statement.
The reason for rethrowing an exception is to allow multiple handlers
access to the exception.
When you rethrow an exception, it will NOT be recaught by the same
catch statement, but it will propagate to the next catch statement.
ITP 120 Java Programming I
108
Patrick Healy
Class #14 – Exception Handling
Rethrowing an Exception
// Rethrow an exception.
class Rethrow {
public static void genException( ) {
// Note: array numer is longer than array denom
int numer[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 };
int denom[ ] = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
ITP 120 Java Programming I
109
Patrick Healy
Class #14 – Exception Handling
Rethrowing an Exception
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
throw exc; // Rethrow the exception !
}
}
}
ITP 120 Java Programming I
110
Patrick Healy
Class #14 – Exception Handling
Rethrowing an Exception
public class RethrowDemo {
public static void main(String[ ] args) {
try {
Rethrow.genException(); // Class Rethrow, method genException()
}
catch (ArrayIndexOutOfBoundsException exc) {
// recatch exception
System.out.println("Fatal error: program terminated.");
}
} // End of main method
} // End of class RethrowDemo
ITP 120 Java Programming I
111
Patrick Healy
Class #14 – Exception Handling
Rethrowing an Exception
In the previous program, divide-by-zero errors are handled locally by
the genException( ) method, but an array boundary error is rethrown.
The array boundary error is caught by the main( ) method
Output from the program RethrowDemo.java:
4 / 2 is 2
Can’t divide by zero !
16 / 4 is 4
32 / 4 is 8
Can’t divide by zero !
128 / 8 is 16
No matching element found
Fatal error – program terminated
ITP 120 Java Programming I
112
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
Sometimes you will want to define a block of code that will execute
when the program leaves a try/catch block.
For example, an exception might cause an error that terminates the
current method, causing its premature return.
However, that method may have opened a file or a network connection
that needs to be closed.
Java has a way to handle them: finally
To specify that a block of code to execute when a try/catch block is
exited, include a finally block at the end of the try/catch sequence.
ITP 120 Java Programming I
113
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
General form of a try/catch that includes finally:
try
{ // Block of code to monitor for errors… }
catch (ExcepType1 exObj1)
{ // Handler for ExceptionType1 }
catch (ExcepType2 exObj2)
{ // Handler for ExceptionType2 }
finally { // finally code goes here … }
ITP 120 Java Programming I
114
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
A try – catch block can be structured as try-catch-finally
try
{ ………. }
catch ( Exception ex )
{ ………… }
finally { ………… }
finally indicates that after you finish handling the exception, perform
these last actions. Or, even if the exception was not thrown or
handled, perform the actions anyway.
ITP 120 Java Programming I
115
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
The finally block will be executed whenever execution leaves a
try/catch block, no matter what conditions cause it.
The last code to be executed is the code in the finally block
ITP 120 Java Programming I
116
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
public class UseFinally { // Use finally
public static void genException(int num) {
int t;
int nums[ ] = new int[20]; // 20 numbers in array “nums”
System.out.println("Receiving " + num );
try {
switch(num) {
case 0:
t = 10 / num; // Generate divide-by-zero error (num is zero)
break;
case 1:
nums[25] = 445; // Generate array index of out bounds error.
break;
case 2:
return; // return from try block } } }
ITP 120 Java Programming I
117
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
return; // return from catch
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
finally
{ System.out.println(“In finally block Leaving try."); }
} // End of method genException()
} // End of class UseFinally
ITP 120 Java Programming I
118
Patrick Healy
Class #14 – Exception Handling
Using the keyword finally
Output from the previous program: UseFinally.java
Receiving 0
Can’t divide by Zero!
Leaving try. (message from finally block)
Receiving 1
No matching element found.
Leaving try. (message from finally block)
Receiving 2 (merely return from try block)
In finally block Leaving try. (message from finally block)
ITP 120 Java Programming I
119
Patrick Healy
Class #14 – Exception Handling
Using Keyword throws
In some cases, if a method generates an exception that is does not
handle, it must declare the exception in a throws clause.
The general form of a method that includes a throws clause is:
return-type methodName(parameter list) throws exception-list
{ // body of the method here }
Here, exception-list is a comma-separated list of exceptions that
the method might throw outside of itself.
Example:
public void someMethod() throws Exception1, Exception2, Exception3
ITP 120 Java Programming I
120
Patrick Healy
Class #14 – Exception Handling
Using Keyword throws
In preceding examples, you did not need to specify a throws clause
because exceptions that are subclasses of Error or RuntimeException
do NOT need to be specified in a throws list.
Java simply assumes that a method may throw one.
All other types of exceptions must be declared.
When performing keyboard input, you should add the clause:
throws java.io.IOException to the main( ) method.
ITP 120 Java Programming I
121
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
The usefulness of exceptions really stems from programs being able to
report any type of problem encountered.
Custom exceptions can be created by inheriting from any Exception
class.
For example we can create an exception to report insufficient funds
when we try to withdraw too much money from an account.
ITP 120 Java Programming I
122
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
Example 18.4 Insufficient Funds Exception (Custom Exception)
public class InsufficientFundsException extends Exception( )
{
public InsufficientFundsException( ) // Default constructor
{
super( “Insufficient funds to complete transaction” );
}
public InsufficientFundsException( String message )
{
super( message ); // Constructor with message parameter
}
}
ITP 120 Java Programming I
123
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
Example 18.4 Continued
// Account class
public class Account {
// include data members of Account class here
// include constructors here
// include other methods except withdraw which might throw exceptions
// Next line of code: claiming an exception (throws)
public void withDraw( double amount ) throws InsufficientFundsException( )
{ // Next line of code: throwing an exception (throw)
if ( amount > balance ) throw new InsufficientFundsException( );
else
balance = balance – amount;
} // End of method withDraw
} // End of class Account
ITP 120 Java Programming I
124
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
Note that the withdraw method of Account class in Example 18.4 has
declared that it might throw an exception
Note the difference between the keywords throw and throws
Any call to the withdraw method must be enclosed in a try-catch block
Because the caller must be ready to handle the exception if it is
thrown.
ITP 120 Java Programming I
125
Patrick Healy
Class #14 – Exception Handling
Refresher: throw & throws
Claiming an Exception (“throws”)
Every method must state the types of exceptions it can encounter.
The term claiming an exception tells the compiler what can go wrong.
public void someMethod( ) throws IOException
Throwing an Exception (“throw”)
When a program statement causes an error, the method containing he
statement creates an exception object and passes it on to the system.
The exception object contains information about the exception
including the exception type and the state of the program when the
error occurred.
The Java code that handles the error is the exception handler.
ITP 120 Java Programming I
126
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
Here is another example of a custom exception which is named
NonIntResultException.
NonIntResultException which is generated when the result of dividing
two integer values produces a result with a fractional component.
The method toString( ) is overridden which allows the description of the
exception to be displayed using the println( ) method
See the next slide 
ITP 120 Java Programming I
127
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
// Create and use a custom exception.
class NonIntResultException extends Exception
{
int n;
int d;
NonIntResultException(int i, int j) // Constructor with parameters
{ n = i;
d = j; }
ITP 120 Java Programming I
128
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
public String toString( ) {
return "Result of " + n + " / " + d +
" is non-integer.";
}
} // End of class NonIntResultException
ITP 120 Java Programming I
129
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
class CustomExceptDemo {
public static void main(String[ ] args) {
// array numer has some odd values which yield non integer results
// when dividing one integer by another.
int numer [ ] = { 4, 8, 15, 32, 64, 127, 256, 512 };
int denom[ ] = { 2, 0, 4, 4, 0, 8 };
ITP 120 Java Programming I
130
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
for(int i=0; I < numer.length; i++) {
try
{
if( (numer[i] % 2) != 0)
throw new
NonIntResultException(numer[i], denom[i]);
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
ITP 120 Java Programming I
131
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
catch (NonIntResultException ex) {
System.out.println( “Exception: “ + ex.getMessage( ));
}
} // End of for loop
} // End of main method
} // End of class CustomExceptDemo
ITP 120 Java Programming I
132
Patrick Healy
Class #14 – Exception Handling
Creating Custom Exceptions
The output from the previous program is:
4 / 2 is 2
Can’t divide by Zero!
Result of 15 / 4 is non-integer.
32 / 4 is 8
Can’t divide by Zero!
Result of 127 / 8 is non-integer.
No matching element found.
No matching element found.
Cautions When Using
Exceptions !
Exception handling separates error-handling
code from normal programming tasks, thus
making programs easier to read and to modify.
But, exception handling usually requires more
time and resources because it requires
instantiating a new exception object, rolling back
the call stack, and propagating the errors to the
calling methods.
Assertions [ Optional ]
The following section on Assertions is OPTIONAL
Assertions [ Optional ]
An assertion is a Java statement that enables
you to assert an assumption about your
program. An assertion contains a Boolean
expression that should be true during
program execution. Assertions can be used to
assure program correctness and avoid logic
errors.
Declaring Assertions
An assertion is declared using the new Java keyword
assert in JDK 1.4 as follows:
assert assertion; or
assert assertion : detailMessage;
where assertion is a Boolean expression and
detailMessage is a primitive-type or an Object value.
Executing Assertions
When an assertion statement is executed, Java evaluates the
assertion. If it is false, an AssertionError will be thrown. The
AssertionError class has a no-arg constructor and seven
overloaded single-argument constructors of type int, long, float,
double, boolean, char, and Object.
For the first assert statement with no detail message, the no-arg
constructor of AssertionError is used. For the second assert
statement with a detail message, an appropriate AssertionError
constructor is used to match the data type of the message. Since
AssertionError is a subclass of Error, when an assertion becomes
false, the program displays a message on the console and exits.
Executing Assertions Example
public class AssertionDemo {
public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i < 10; i++) {
sum += i;
}
assert i == 10;
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
}
}
Compiling Programs with
Assertions
Since assert is a new Java keyword introduced in
JDK 1.4, you have to compile the program using a
JDK 1.4 compiler. Furthermore, you need to
include the switch –source 1.4 in the compiler
command as follows:
javac –source 1.4 AssertionDemo.java
NOTE: If you use JDK 1.5, there is no need to use
the –source 1.4 option in the command.
Running Programs with
Assertions
By default, the assertions are disabled at runtime. To
enable it, use the switch –enableassertions, or –ea for
short, as follows:
java –ea AssertionDemo
Assertions can be selectively enabled or disabled at class
level or package level. The disable switch is –
disableassertions or –da for short. For example, the
following command enables assertions in package
package1 and disables assertions in class Class1.
java –ea:package1 –da:Class1 AssertionDemo
Using Exception Handling or
Assertions
Assertion should not be used to replace exception
handling. Exception handling deals with unusual
circumstances during program execution. Assertions are
to assure the correctness of the program. Exception
handling addresses robustness and assertion addresses
correctness. Like exception handling, assertions are not
used for normal tests, but for internal consistency and
validity checks. Assertions are checked at runtime and
can be turned on or off at startup time.
Using Exception Handling or
Assertions, cont.
Do not use assertions for argument checking in public
methods. Valid arguments that may be passed to a public
method are considered to be part of the method’s
contract. The contract must always be obeyed whether
assertions are enabled or disabled. For example, the
following code should be rewritten using exception
handling as shown in Lines 28-35 in Circle.java in Listing
18.1.
public void setRadius(double newRadius) {
assert newRadius >= 0;
radius = newRadius;
}
Using Exception Handling or
Assertions, cont.
Use assertions to reaffirm assumptions. This gives you
more confidence to assure correctness of the program. A
common use of assertions is to replace assumptions with
assertions in the code.
Using Exception Handling or
Assertions, cont.
Another good use of assertions is place assertions in a
switch statement without a default case. For example,
switch (month) {
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: " + month
}
ITP 120 Java Programming I
145
Patrick Healy
Class #14 – Exception Handling
Chapter 17 Demo Programs Exceptions
ExcDemo1.java
ExcDemo3.java
ExcDemo4.java
ExcDemo5.java
ExcTypeMismatch.java TestCircleWithException.java
ExceptionScope.java goes with (CircleWithException.java)
ExcCustomExceptDemo.java ExcDemoInfinity.java
ExcNestedTrys.java ExcFinallyDemo.java
ExcCreatingExceptions.java ExcChainedExceptionDemo.java
ExcOutOfRangeException.java) (goes with ExcCreatingExceptions)
ExcThrowDemo.java JamilGUICalculator.java
ExcRethrow.java ExcProductCodes.java
ExcNotHandled.java ExcCalculatorGUI.java
ITP 120 Java Programming I
146
Patrick Healy
Class #14 – Exception Handling
End of Presentation
Ad

More Related Content

What's hot (19)

Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Java exception-handling
Java exception-handlingJava exception-handling
Java exception-handling
Suresh Kumar Reddy V
 
Unit5 java
Unit5 javaUnit5 java
Unit5 java
mrecedu
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Operators, control statements represented in java
Operators, control statements  represented in javaOperators, control statements  represented in java
Operators, control statements represented in java
TharuniDiddekunta
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
talha ijaz
 
150412 38 beamer methods of binary analysis
150412 38 beamer methods of  binary analysis150412 38 beamer methods of  binary analysis
150412 38 beamer methods of binary analysis
Raghu Palakodety
 
QA Best Practices
QA  Best PracticesQA  Best Practices
QA Best Practices
James York
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
Bala Subra
 
JavaYDL14
JavaYDL14JavaYDL14
JavaYDL14
Terry Yoast
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
Salim M
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Scott Leberknight
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
sshhzap
 
ユニバーサル Windows アプリ開発
ユニバーサル Windows アプリ開発ユニバーサル Windows アプリ開発
ユニバーサル Windows アプリ開発
Akira Onishi
 
Exception Handling in Perl
Exception Handling in PerlException Handling in Perl
Exception Handling in Perl
Ian Kluft
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Unit5 java
Unit5 javaUnit5 java
Unit5 java
mrecedu
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Operators, control statements represented in java
Operators, control statements  represented in javaOperators, control statements  represented in java
Operators, control statements represented in java
TharuniDiddekunta
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
150412 38 beamer methods of binary analysis
150412 38 beamer methods of  binary analysis150412 38 beamer methods of  binary analysis
150412 38 beamer methods of binary analysis
Raghu Palakodety
 
QA Best Practices
QA  Best PracticesQA  Best Practices
QA Best Practices
James York
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
Bala Subra
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
Salim M
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
sshhzap
 
ユニバーサル Windows アプリ開発
ユニバーサル Windows アプリ開発ユニバーサル Windows アプリ開発
ユニバーサル Windows アプリ開発
Akira Onishi
 
Exception Handling in Perl
Exception Handling in PerlException Handling in Perl
Exception Handling in Perl
Ian Kluft
 

Viewers also liked (10)

Itp
ItpItp
Itp
Vikas Karwasara
 
idiopathic thrombocytopinic purpura
idiopathic thrombocytopinic purpuraidiopathic thrombocytopinic purpura
idiopathic thrombocytopinic purpura
dr yogendra vijay
 
Idiopathic Thrombocytopenic Purpura
Idiopathic Thrombocytopenic PurpuraIdiopathic Thrombocytopenic Purpura
Idiopathic Thrombocytopenic Purpura
Dang Thanh Tuan
 
ITP by dr. Mohib Ali
ITP by dr. Mohib AliITP by dr. Mohib Ali
ITP by dr. Mohib Ali
Mohib Ali
 
ITP
ITPITP
ITP
Asma Sherazi
 
Idiopathic Thrombocytopenic Purpura
Idiopathic Thrombocytopenic PurpuraIdiopathic Thrombocytopenic Purpura
Idiopathic Thrombocytopenic Purpura
jayatheeswaranvijayakumar
 
ITP (IDIOPATIK THROMBOSITOPENIK PURPURA)
ITP (IDIOPATIK THROMBOSITOPENIK PURPURA)ITP (IDIOPATIK THROMBOSITOPENIK PURPURA)
ITP (IDIOPATIK THROMBOSITOPENIK PURPURA)
Ariandita Atias
 
23 Ppt Itp
23 Ppt Itp23 Ppt Itp
23 Ppt Itp
ghalan
 
Idiopathic (autoimmune) Thrombocytopenic Purpura
Idiopathic (autoimmune) Thrombocytopenic PurpuraIdiopathic (autoimmune) Thrombocytopenic Purpura
Idiopathic (autoimmune) Thrombocytopenic Purpura
Dr. Saad Saleh Al Ani
 
Itp
ItpItp
Itp
Joselle Balasa
 
Ad

Similar to Itp 120 Chapt 18 2009 Exceptions & Assertions (20)

Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
JAVA Presenttation topics Programs.pptx
JAVA  Presenttation topics Programs.pptxJAVA  Presenttation topics Programs.pptx
JAVA Presenttation topics Programs.pptx
RitikSharma685066
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
Fraz Bakhsh
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
JAVA Presenttation topics Programs.pptx
JAVA  Presenttation topics Programs.pptxJAVA  Presenttation topics Programs.pptx
JAVA Presenttation topics Programs.pptx
RitikSharma685066
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
JAYAPRIYAR7
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogrammingoop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Ad

More from phanleson (20)

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
phanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
phanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
phanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
phanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
phanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
phanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
phanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
phanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
phanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
phanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
phanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
phanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
phanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
phanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
phanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
phanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
phanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
phanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
phanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
phanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
phanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
phanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
phanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
phanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
phanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
phanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
phanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
phanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
phanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
phanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
phanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
phanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
phanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
phanleson
 

Itp 120 Chapt 18 2009 Exceptions & Assertions

  • 1. Chapter 18Chapter 18 Exceptions &Exceptions & AssertionsAssertions Java I ITP 120Java I ITP 120
  • 2. ITP 120 Java Programming I 2 Patrick Healy Class #14 – Exception Handling Chapter Objectives Understand the concept of exception handling Become familiar with exception types Learn how to use the try-catch block to handle exceptions Learn how to throw exceptions Understand the finally block Learn how to create and use custom exceptions Look at the Sum of Digits (Exercise 5.2) program with exceptions See handout for students
  • 3. ITP 120 Java Programming I 3 Patrick Healy Class #14 – Exception Handling Categories of Errors There are three categories or types of errors: (1) Syntax errors (2) Logic errors (sometimes called: semantic errors) (3) Runtime errors Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Logic errors occur when a program doesn't perform the way it was intended to. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out.
  • 4. Runtime Errors import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); } } If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated. Terminated. 1 2 3 4 5 6 7 8 9 10 11 12 13
  • 5. Catching Runtime Errors import java.util.*; public class HandleExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); boolean continueInput = true; do { try { System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextLine(); // discard input } } while (continueInput); } } If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch 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 13
  • 6. ITP 120 Java Programming I 6 Patrick Healy Class #14 – Exception HandlingCatching Runtime Errors (Another example) import javax.swing.JOptionPane; public class Test { public static void main(String[] args) { try { String input = JOptionPane.showInputDialog(null, "Please enter an integer"); int number = Integer.parseInt(input); // Display the result JOptionPane.showMessageDialog(null, "The number entered is " + number); } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Incorrect input: an integer is required"); } System.out.println("Execution continues ..."); System.exit(0); } } If an exception occurs on this line, the rest lines in the try clause are skipped and the control is transferred to the catch clause. After the exception is caught and processed, the control is transferred to the next statement after the try-catch block.
  • 7. ITP 120 Java Programming I 7 Patrick Healy Class #14 – Exception Handling Exception Handling : Exceptions vs Errors An exception is an object that defines an unusual or erroneous situation An exception is thrown by a program or the run-time environment and can be caught and handled if desired. The DIFFERENCE between an ERROR and an EXCEPTION: An error is similar to an exception except that an error generally represents an unrecoverable situation and cannot be caught.
  • 8. ITP 120 Java Programming I 8 Patrick Healy Class #14 – Exception Handling Exception Handling : Examples of ProblemsExamples of situations that cause exceptions to be thrown: (1) Attempting to divide by zero: x = 126.57 / 0.0 (2) An array index is out of bounds (3) A specified file could not be found (4) An I/O operation could not be completed normally (5) An attempt was made to follow a null reference (to an object)
  • 9. ITP 120 Java Programming I 9 Patrick Healy Class #14 – Exception Handling Exception Handling : Dealing with Problems A Java program can be designed to: (1) Not handle the exception at all. (2) Handle the exception where it occurs. OR: (3) Handle the exception at another place in the program.
  • 10. ITP 120 Java Programming I 10 Patrick Healy Class #14 – Exception Handling Exception Handling Exception handling is generally used to handle abnormal events in a program. When a method encounters a problem that disrupts the normal flow, it can cause the program to CRASH ! But with exception handling, the method can throw an exception which informs the caller that a problem occurred allowing the caller to perform alternative actions. Exception handling enables more robust programming by providing ways of recovering from errors or problems.
  • 11. ITP 120 Java Programming I 11 Patrick Healy Class #14 – Exception Handling Exceptions 2 types: Checked vs Unchecked Exception handling streamlines error handling by allowing your program to define a block of code, called an exception handler that is executed automatically when an error occurs. Java defines standard exceptions for common errors such as divide- by-zero and file-not-found. (these are Unchecked exceptions and beyond the control of the programmer) Checked exceptions CAN be handled in Java programs. To respond to these errors, your program must watch for and handle these exceptions.
  • 12. ITP 120 Java Programming I 12 Patrick Healy Class #14 – Exception Handling Exceptions and Exception Types
  • 13. ITP 120 Java Programming I 13 Patrick Healy Class #14 – Exception HandlingSystem Errors (Note: click the mouse to see fly-ins) System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
  • 14. ITP 120 Java Programming I 14 Patrick Healy Class #14 – Exception HandlingExceptions (Note: click the mouse to see fly-ins) Exceptions are represented in the Exception class that describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • 15. ITP 120 Java Programming I 15 Patrick Healy Class #14 – Exception HandlingRuntime Exceptions (Note: click the mouse to see fly-ins) Runtime exceptions are represented in the RuntimeException class that describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
  • 16. ITP 120 Java Programming I 16 Patrick Healy Class #14 – Exception Handling Java’s Built-in UnChecked Exceptions Exception Meaning ArithmeticException Arithmetic error; divide-by-zero ArrayIndexOutOfBoundsException Array index is out of bounds ArrayStoreException Assignment of an array element is an incompatible type. ClassCastException Invalid cast operation IllegalArgumentException Illegal argument used to invoke a method IndexOutOfBoundsException Some type of index is out of bounds
  • 17. ITP 120 Java Programming I 17 Patrick Healy Class #14 – Exception Handling Java’s Built-in UnChecked Exceptions Exception Meaning NegativeArraySizeException Array created with a negative size NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format StringIndexOutOfBounds Attempt to index outside the bounds of a string
  • 18. ITP 120 Java Programming I 18 Patrick Healy Class #14 – Exception Handling Java’s Built-in Checked Exceptions Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied Instantiation Exception Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread NoSuchMethodException Method does not exist
  • 19. Checked vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as UNCHECKED EXCEPTIONS. All other exceptions are known as CHECKED EXCEPTIONS, meaning that the compiler forces the programmer to check and deal with the exceptions.
  • 20. Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.
  • 21. Declaring Exceptions Every method should state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException
  • 22. Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new SomeException(); SomeException ex = new SomeException(); throw ex;
  • 23. Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentExceptionthrows IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
  • 24. Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; }
  • 25. Catching Exceptions main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } statement2; } method1 { ... try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; } statement4; } method2 { ... try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; } statement6; } An exception is thrown in method3
  • 26. ITP 120 Java Programming I 26 Patrick Healy Class #14 – Exception Handling Catching Exceptions Consider the scenario on the previous graphic slide: Suppose an exception occurs in the try-catch block that contains a call to method3. If the exception type is Exception3, it is caught by the catch clause for handling ex3 in Method 2 If the exception type is Exception2, it is caught by the catch clause for handling ex2 in Method 1 If the exception type is Exception1, it is caught by the catch clause for handling ex1 in the main method. If the exception type is NOT Exception1, Exception2, or Exception3, the program terminates.
  • 27. ITP 120 Java Programming I 27 Patrick Healy Class #14 – Exception Handling Catching Exceptions: Previous slide Still referring to the scenario on the previous graphic slide: If the exception type is Exception3, then statement 5 is skipped. If the exception type is Exception2, then statements 3 & 5 are skipped. If the exception type is Exception1, then statements 1,3 & 5 are skipped.
  • 28. ITP 120 Java Programming I 28 Patrick Healy Class #14 – Exception Handling Catching Exceptions in Graphics Programs Note: An exception is ignored when … an exception of a subclass of class Exception occurs in a graphics program, Java prints the error message on the monitor, but the program goes back to its GUI processing loop to run continuously.
  • 29. Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in figure (a) OR figure (b). void p1() { try { p2(); } catch (IOException ex) { ... } } (a) (b) void p1() throws IOException { p2(); }
  • 30. Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
  • 31. Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
  • 32. Trace Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed
  • 33. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2
  • 34. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled here
  • 35. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block statements are always executed.
  • 36. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method in the program is now executed.
  • 37. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; statement2 throws an exception of type Exception2.
  • 38. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handle the exception
  • 39. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Execute the finally block statements
  • 40. Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Rethrow the exception and control is transferred to the calling statement in the method
  • 41. ITP 120 Java Programming I 41 Patrick Healy Class #14 – Exception Handling Claiming & Throwing Exceptions Claiming an Exception (“throws”) Every method must state the types of exceptions it can encounter. The term claiming an exception tells the compiler what can go wrong. public void someMethod( ) throws IOException Throwing an Exception (“throw”) When a program statement causes an error, the method containing he statement creates an exception object and passes it on to the system. The exception object contains information about the exception including the exception type and the state of the program when the error occurred. The Java code that handles the error is the exception handler.
  • 42. ITP 120 Java Programming I 42 Patrick Healy Class #14 – Exception Handling GUI Calculator Code Fragment public void calculator(int operator){ //Using try -catch block for improperly formatted input. try { double num1 = new Double(jtfNumber1.getText().trim()).doubleValue(); double num2 = new Double(jtfNumber2.getText().trim()).doubleValue(); double result = 0.0; switch (operator) { case 0 : result = (num1 + num2); break; case 1 : result = (num1 - num2); break; case 2 : result = (num1 * num2); break; case 3 : result = (num1 * 1.0 / num2); break; } String str = String.format("%1.4f", result); jtfResult.setText(String.valueOf(str)); // Process improperly formatted input. } catch (NumberFormatException numberError){ JOptionPane.showMessageDialog(this, "You must enter two values", "Invalid Number Format", JOptionPane.ERROR_MESSAGE ); clearFields(); } }//End of calculate-method.
  • 43. ITP 120 Java Programming I 43 Patrick Healy Class #14 – Exception Handling The JVM handles a Divide Exception ! // ExcDemoInfinity.java import javax.swing.JOptionPane; public class ExcDemoInfinity { public static void main(String args[]) { double result; String output = ""; result = 1234.56 / 0.0; // Try to divide by zero try { System.out.println( result ); // Just the word "Infinity" is printed } catch (Exception ex) { System.out.println("Exception message is never printed" + ex.getMessage()); } System.out.println("End of program"); output = "The word "Infinity" is printed" + "n" + "Exception was handled by the JVM"; JOptionPane.showMessageDialog(null,output); } // End of main method } // End of class ExcDemoInfinity
  • 44. ITP 120 Java Programming I 44 Patrick Healy Class #14 – Exception Handling Claiming & Throwing Exceptions Catching an Exception This is the process of finding an exception handler. The exception handler must match the type of exception thrown. ( see demo program ExcTypeMismatch.java ) If no matching handler is found, the program terminates.
  • 45. ITP 120 Java Programming I 45 Patrick Healy Class #14 – Exception Handling Claiming & Throwing Exceptions: throws & throw Use the keyword throws to claim an exception. Example: public void myDivideMethod ( double d1, double d2 ) throws RunTimeException Use the keyword throw to throw an exception Example: if( checkAmount > availableBalance) throw new InsufficientFundsException( );
  • 46. ITP 120 Java Programming I 46 Patrick Healy Class #14 – Exception Handling Throwing Exceptions In the method that has claimed the exception, you can throw an object of the exception if the exception arises. The following is the syntax to throw an exception: throw new MyException ( ); Or: MyException myEx = new MyException ( ); throw myEx;
  • 47. ITP 120 Java Programming I 47 Patrick Healy Class #14 – Exception Handling Catching, Claiming, and Throwing Exceptions method1() { try { invoke method2; } catch (Exception ex) { Process exception; } } method2() throws Exception { if (an error occurs) { throw new Exception(); } } catch exception throw exception claim exception
  • 48. ITP 120 Java Programming I 48 Patrick Healy Class #14 – Exception Handling Some Constructors & Methods of class Throwable public Throwable ( ) Default constructor Creates an instance of Throwable with an empty message string public Throwable (String messageString) Constructor with parameters Creates an instance of Throwable with the message string specified by the parameter messageString
  • 49. ITP 120 Java Programming I 49 Patrick Healy Class #14 – Exception Handling Some Constructors & Methods of class Throwable public String getMessage( ) Returns the detailed message stored in the object public void printStackTrace( ) Method to print the stack trace showing the sequence of method calls when an exception occurs
  • 50. ITP 120 Java Programming I 50 Patrick Healy Class #14 – Exception Handling Some Constructors & Methods of class Throwable public void printStackTrace(PrintWriter stream ) Method to print the stack trace showing the sequence of method calls when an exception occurs. Output is sent to the stream specified by parameter stream. public String toString( ) Returns a string representation of the Throwable object
  • 51. ITP 120 Java Programming I 51 Patrick Healy Class #14 – Exception Handling The Exception Hierarchy In Java, all exceptions are represented in the various classes. All exception classes are derived from a class called Throwable The two direct subclasses of the class Throwable are: Exception and Error Exceptions of type Error are related to errors that occur in the Java Virtual Machine (JVM) itself and NOT in your program. Error type exceptions are BEYOND YOUR CONTROL ! Exceptions of type Exception are errors that result from YOUR program’s activity. RunTimeException is an important subclass of subclass Exception.
  • 52. ITP 120 Java Programming I 52 Patrick Healy Class #14 – Exception Handling Java’s Built-in Exceptions Inside the java.lang package, Java defines several exception classes. The most general of these exceptions are subclasses of the standard type RuntimeException. Since java.lang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available. The unchecked exceptions defined in java.lang are listed on subsequent slides in this presentation. Unchecked exceptions are exceptions that the compiler does NOT check to see if a method handles or throws those exceptions. Checked exceptions MUST be caught and handled.
  • 53. ITP 120 Java Programming I 53 Patrick Healy Class #14 – Exception Handling 2 Types of Exceptions: Checked & Unchecked  UNCHECKED EXCEPTIONS: (NOT checked by the compiler) Do NOT have to be caught. (Beyond your control)  CHECKED EXCEPTIONS: (Checked by the compiler) They MUST be caught and handled.
  • 54. ITP 120 Java Programming I 54 Patrick Healy Class #14 – Exception Handling About Checked & Unchecked Exceptions… Checked Exceptions (Checked by the Java compiler) Any exception that can be analyzed by the compiler is called a checked exception. For example, IOExceptions are checked exceptions. Since the methods read and readLine throw IOException, these methods throw checked exceptions. When the compiler encounters these method calls, it checks whether the program handles IOException, or reports them by throwing them. Having the compiler check for exceptions reduces the number of exceptions not properly handled by the program.
  • 55. ITP 120 Java Programming I 55 Patrick Healy Class #14 – Exception Handling About Checked & Unchecked Exceptions… Unchecked exceptions are those NOT checked by the Java compiler. When a program is being compiled, it may NOT be possible for the compiler to determine if exceptions such as division-by-zero or array- index-out-of-bounds will occur. Therefore, to improve the reliability and correctness of Java programs, programmers should check for these types of exceptions.
  • 56. ITP 120 Java Programming I 56 Patrick Healy Class #14 – Exception Handling Java’s Built-in UnChecked Exceptions Exception Meaning ArithmeticException Arithmetic error; divide-by-zero ArrayIndexOutOfBoundsException Array index is out of bounds ArrayStoreException Assignment of an array element is an incompatible type. ClassCastException Invalid cast operation IllegalArgumentException Illegal argument used to invoke a method IndexOutOfBoundsException Some type of index is out of bounds
  • 57. ITP 120 Java Programming I 57 Patrick Healy Class #14 – Exception Handling Java’s Built-in UnChecked Exceptions Exception Meaning NegativeArraySizeException Array created with a negative size NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format StringIndexOutOfBounds Attempt to index outside the bounds of a string
  • 58. Exceptions in GUI Applications The methods are executed on the threads. If an exception occurs on a thread, the thread is terminated if the exception is not handled. However, the other threads in the application are not affected. There are several threads running to support a GUI application. A thread is launched to execute an event handler (e.g., the actionPerformed method for the ActionEvent). If an exception occurs during the execution of a GUI event handler, the thread is terminated if the exception is not handled. Interestingly, Java prints the error message on the console, but does not terminate the application. The program goes back to its user-interface-processing loop to run continuously.
  • 59. Example: Exceptions in GUIs An error message appears on the console, but the GUI application continues running. Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields Number 1 and Number 2. The division of Number 1 and Number 2 is displayed in the Result field when the Divide button is clicked.
  • 60. ITP 120 Java Programming I 60 Patrick Healy Class #14 – Exception Handling Exceptions thrown by methods of class Integer Remember: Java programs accept only STRINGS as input. Numbers, integer or decimal, are entered as strings ! The method parseInt of the class Integer is used to convert an integer string into the equivalent integer. If the string contains any character that is not a number, the method parseInt will throw an exception: NumberFormatException (an unchecked exception) Also, the method parseDouble will throw an exception if the string does not contain a valid number. double dblNumber = Double.parseDouble (inputString);
  • 61. ITP 120 Java Programming I 61 Patrick Healy Class #14 – Exception Handling Java’s Built-in Checked Exceptions Exception Meaning ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied Instantiation Exception Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread NoSuchMethodException Method does not exist
  • 62. ITP 120 Java Programming I 62 Patrick Healy Class #14 – Exception Handling Exception Handling Fundamentals Java exception handling is managed using five keywords: try, catch, throw, throws, finally Program statements that you want to monitor are contained within a try block. If an exception occurs within the try block, it is thrown. Your program code can catch this exception using a catch statement and handle it in some rational manner. To manually throw an exception, use the keyword throw. Any code that absolutely must be executed upon exiting from a try block is put in a finally block.
  • 63. ITP 120 Java Programming I 63 Patrick Healy Class #14 – Exception Handling Exception Handling Fundamentals To manually throw an exception, use the keyword throw. public void setRadius ( double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( “ THE CIRCLE’S RADIUS CANNOT BE NEGATIVE !"); } Any code that absolutely must be executed upon exiting from a try block is put in a finally block. (see next slide )
  • 64. ITP 120 Java Programming I 64 Patrick Healy Class #14 – Exception Handling Handling Exceptions within a Program The general syntax of the try/catch/finally block is: try { // statements that may throw exceptions } catch (ExceptionClassName1 ex1) { // exception handler code statements } continued on next page 
  • 65. ITP 120 Java Programming I 65 Patrick Healy Class #14 – Exception Handling Handling Exceptions within a Program (cont.) catch (ExceptionClassName2 ex2) { // exception handler code } … catch (ExceptionClassName3 ex3) { // exception handler code } finally // The finally block is always executed ! { // finally block statements }
  • 66. ITP 120 Java Programming I 66 Patrick Healy Class #14 – Exception Handling Handling Exceptions within a Program (cont.) Consider the following catch block: catch ( ArithmeticException ex ) { System.out.println(“Error: “ + ex.getMessage( ) ); } The catch block catches an exception of type ArithmeticException which is a runtime exception. The identifier ex is an identifier is a reference variable of the type ArithmeticException.
  • 67. ITP 120 Java Programming I 67 Patrick Healy Class #14 – Exception Handling Handling Exceptions within a Program (cont.) If an ArithmeticException is thrown by the associated try block, the reference parameter ex contains the address of the exception thrown by the try block. The object ex stores a detailed description of the the thrown exception. The method getMessage( ) or the method toString( ) will retrieve and print the message containing the description of the thrown exception.
  • 68. ITP 120 Java Programming I 68 Patrick Healy Class #14 – Exception Handling Handling Exceptions within a Program (cont.)Examples: catch ( ArithmeticException ex ) { // Below: Use either getMessage( ) or toString( ) System.out.println(“Error: “ + ex.getMessage( ) ); System.out.println(“Error: “ + ex.toString( ) ); } catch ( NumberFormatException numEx ) { System.out.println(“Error: “ + numEx.getMessage( ) ); }
  • 69. ITP 120 Java Programming I 69 Patrick Healy Class #14 – Exception Handling Exception Handling Example 18.1 This program aborts due to an attempt to divide by zero public class TestException1 { public static void main( String[ ] args ) { System.out.println ( 120.5 / 0); // Division by zero } // End main method } // End of class TestException1
  • 70. ITP 120 Java Programming I 70 Patrick Healy Class #14 – Exception Handling Exception Handling Example 18.2 This program handles the divide by zero error when it occurs public class TestException2 { public static void main( String[ ] args ) { try { System.out.println( 120 / 0 ); // Divide by zero attempted } catch( Exception ex ) // Exception is a class; ex is an object of // class Exception { System.out.println(“Error: “ + ex.getMessage()); } System.out.println(“Continued execution after handling the error” ); } // End main method } // End of class TestException2
  • 71. ITP 120 Java Programming I 71 Patrick Healy Class #14 – Exception Handling Exception Handling Exceptions are thrown by methods But … not all methods throw exceptions If a method throws exceptions, it is the responsibility of the caller to handle the problems reported by the method. Generally, methods throw exceptions to report problems or any events (other than the expected one) to the caller of the method
  • 72. ITP 120 Java Programming I 72 Patrick Healy Class #14 – Exception Handling Exceptions and Exception Types There is a hierarchy of exceptions with Throwable being at the top Two types of exceptions: Checked Exceptions and Unchecked Exceptions. Checked Exceptions are exceptions that must be caught Unchecked Exceptions do NOT have to be caught Examples of unchecked exceptions: RuntimeException and its subclasses such as: ArithmeticException, IndexOutOfBoundsException, NullPointerException
  • 73. ITP 120 Java Programming I 73 Patrick Healy Class #14 – Exception Handling Claiming an Exception Java’s Exception handling is based on three operations Claiming an exception Throwing an exception Catching an exception Claiming an exception By using the keyword throws in a method declaration to inform the compiler that the method might throw an exception Example: public void Amethod() throws IOException A method also lets any caller know to expect IOException may be thrown A method may throw more than one exception. It must include all of them in the declaration, each separated by comma public void Bmethod() throws Exception1, Exception2, Exception3
  • 74. ITP 120 Java Programming I 74 Patrick Healy Class #14 – Exception Handling Throwing an Exception After a method declares that it might throw an exception, it is free to throw it from inside the method. public void Amethod( ) throws IOException { // Doing some operations and something goes wrong throw new IOException(); } A method can throw more than one exception since any number of things can go wrong.
  • 75. ITP 120 Java Programming I 75 Patrick Healy Class #14 – Exception Handling Catching an Exception The caller of a method which throws an exception must be prepared to catch the exception by using the try-catch block. try { Bmethod( ); // Bmethod might throw any of the exceptions caught below: } catch(Exception1 ex1) { // Handle the problem here } catch(Exception2 ex2) { // handle the problem here } catch(Exception3 ex3) { // Handle the problem here }
  • 76. ITP 120 Java Programming I 76 Patrick Healy Class #14 – Exception Handling Exception Handling Example 18.3 public class Divide { private double number1; private double number2; Divide( ) { // Default constructor number1 = 1; number2 = 2; } Divide( double num1, double num2) //Constructor with parameters { number1 = num1; number2 = num2; } public double divideMethod( ) throws ArithmeticException { if ( number2 == 0 ) throw new ArithmeticException(“The denominator is zero ‘); else return number1 / number2; // It is safe to carry out the division. } }
  • 77. ITP 120 Java Programming I 77 Patrick Healy Class #14 – Exception Handling Example 18.3 continued public class TestDivide { public static void main( String[ ] args) { Divide myDivider = new Divide( 5, 3); // Create new object try { System.out.println(myDivider.divideMethod()); } catch(ArithmeticException ex) { System.out.println (“Error: “ + ex.getMessage() ); } } }
  • 78. ITP 120 Java Programming I 78 Patrick Healy Class #14 – Exception Handling Example 18.3 continued public class TestDivide { // If the first statement in a “try” block causes an exception, // the next statement will NOT be executed. public static void main( String[ ] args) { Divide myDivider = new Divide( 21,0); // Instantiate 1st object Divide myDivider2 = new Divide (16, 4); // Instantiate 2nd object try { System.out.println(myDivider.divideMethod( )); // Causes divide exception System.out.println(myDivider2.divideMethod( )); // Won’t be executed ! } catch(ArithmeticException ex) { System.out.println (“Error: “ + ex.getMessage() ); } } }
  • 79. ITP 120 Java Programming I 79 Patrick Healy Class #14 – Exception Handling Using try and catch Keywords try and catch work together; you cannot have a try without a catch or a catch without a try. The general form of the try/catch exception follows: try { // (Block of code to monitor for errors) } catch (ExceptionType1 exOb) { // Handler for ExceptionType1 } catch (ExceptionType2 exOb) { // Handler for ExceptionType2 }
  • 80. ITP 120 Java Programming I 80 Patrick Healy Class #14 – Exception Handling Using try and catch As the previous general form example shows, there can be more than one catch statement associated with a try. The type of exception determines which catch statement is executed. Only that catch statement is executed; all others are by-passed. When an exception is caught, exOb will receive its value. If NO exception is thrown, then the try block ends normally, and all of the catch statements are bypassed. Execution then resumes with the first statement following the last catch statement Catch statements are executed only if an exception is thrown.
  • 81. ITP 120 Java Programming I 81 Patrick Healy Class #14 – Exception Handling A Simple Exception Example class ExcDemo1 { // Demonstrate exception handling public static void main(String[ ] args) { int nums[ ] = new int[4]; // One-dimensional array of 4 integer numbers try { System.out.println("Before exception is generated."); // Generate an index out-of-bounds exception. nums[7] = 25; // Attempt to store the integer 25 into 8th array position System.out.println("this won't be displayed"); } catch (ArrayIndexOutOfBoundsException ex) { System.out.println(“Error from Java: “ + ex.getMessage( ) ); System.out.println("Index out-of-bounds!"); } // End of catch statement System.out.println("After catch statement."); } // End of main method } // End of class ExcDemo1
  • 82. ITP 120 Java Programming I 82 Patrick Healy Class #14 – Exception Handling A Simple Exception example (continued) Output from running Java program ExcDemo1 Before exception is generated. Error from Java: null Index out-of-bounds! After catch statement.
  • 83. ITP 120 Java Programming I 83 Patrick Healy Class #14 – Exception Handling Another Exception Example: // An exception can be generated by one method and caught by another. public class ExcTest { // See next slide  // Generate an exception. static void genException() // The offending method { int nums[ ] = new int[4]; // Declare an array of integers System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 120; // Attempt to store 120 into the 8th array member System.out.println(“This message won't be displayed !"); } } // End of class ExcTest An
  • 84. ITP 120 Java Programming I 84 Patrick Healy Class #14 – Exception Handling Another Exception Example (continued) class ExcDemo2 { public static void main(String[ ] args) { try { ExcTest . genException ( ); // Use class ExcTest (see previous slide) } catch (ArrayIndexOutOfBoundsException ex) { // catch the exception System.out.println(“Exception: “ + ex.getMessage( ) ); System.out.println("Index out-of-bounds!"); // This is printed } System.out.println("After catch statement."); // This is printed } // End of main method } // End of class ExcDemo2
  • 85. ITP 120 Java Programming I 85 Patrick Healy Class #14 – Exception Handling The Consequences of an Uncaught Exception Catching one of Java’s standard exceptions has a benefit… It prevents abnormal program termination. If your program does NOT catch an exception, then it will be caught by the Java Virtual machine (JVM). But… the JVM’s default exception handler terminates execution and displays a stack trace and error message. In the next example, the index-out-of-bounds exception is NOT caught by the program.
  • 86. ITP 120 Java Programming I 86 Patrick Healy Class #14 – Exception Handling The Consequences of an Uncaught Exception // Let JVM handle the error. class NotHandled { public static void main(String[ ] args) { int nums[ ] = new int[4]; System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 54; // Try to assign a number to the 8th position } // End of main method } // End of class NotHandled
  • 87. ITP 120 Java Programming I 87 Patrick Healy Class #14 – Exception Handling The Consequences of an Uncaught Exception In the previous program, when the array index error occurs, execution is halted, and the following error message is displayed: Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException at NotHandled.main (NotHandled.java:9)
  • 88. ITP 120 Java Programming I 88 Patrick Healy Class #14 – Exception Handling Exception Type must match Type in the catch The type of exception MUST match the type specified in a catch statement. If there is a mismatch, there will be an abnormal program termination. In the next example, the program tries to catch an array boundary error with a catch statement for an ArithmeticException (another of Java’s built-in exceptions) When the array boundary is overrun, an ArrayIndexOutOfBoundsException is generated, but it won’t be caught by the catch statement. Run the Java program ExcTypeMismatch.java to verify.
  • 89. ITP 120 Java Programming I 89 Patrick Healy Class #14 – Exception Handling Exception Type must match Type in the catch Exception Type must match the type in the catch // This won't work! class ExcTypeMismatch { public static void main(String[ ] args) { int [ ] nums = new int[4]; try { System.out.println("Before exception is generated."); // generate an index out-of-bounds exception nums[7] = 55; // Attempt to store 55 into 8th array position System.out.println(“This won't be displayed"); }
  • 90. ITP 120 Java Programming I 90 Patrick Healy Class #14 – Exception Handling Exception Type must match Type in the catch // Can't catch an array boundary error with an ArithmeticException. catch (ArithmeticException exc) // Incorrect exception type { // catch the exception System.out.println("Index out-of-bounds!"); // Incorrect message! } System.out.println("After catch statement."); // Not printed } // End of main method } // End of class
  • 91. ITP 120 Java Programming I 91 Patrick Healy Class #14 – Exception Handling Exceptions Help You to Handle Errors Gracefullypublic class ExcDemo3 { // Handle errors gracefully & continue public static void main(String[ ] args) { int number[ ] = { 4, 8, 16, 32, 64, 128 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 }; for(int i=0; I <number.length; i++) { try { System.out.println(number[i] + " / " + denom[i] + " is " + number[i] / denom[i]); } catch (ArithmeticException ex) { // catch the exception System.out.println("Can't divide by Zero!"); } } // End of for loop } // End of main } // End of class ExcDemo3
  • 92. ITP 120 Java Programming I 92 Patrick Healy Class #14 – Exception Handling Using Multiple Catch Statements You can associate more than one catch statement with a try. This is commonly done. However, each catch statement must catch a different type of exception. In the next example, the program catches two types of errors: array boundary errors divide-by-zero errors.
  • 93. ITP 120 Java Programming I 93 Patrick Healy Class #14 – Exception Handling Using Multiple Catch Statements // Use multiple catch statements. class ExcDemo4 { public static void main(String[ ] args) { // Here, array number is longer than array denom. int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; // 8 elements int denom[ ] = { 2, 0, 4, 4, 0, 8 }; // 6 elements for(int i=0; i<number.length; i++) { try { System.out.println(number[i] + " / " + denom[i] + " is " + number[i]/denom[i]); }
  • 94. ITP 120 Java Programming I 94 Patrick Healy Class #14 – Exception Handling Using Multiple Catch Statements catch (ArithmeticException exc) { // catch the exception System.out.println("Cannot divide by Zero!"); } catch (ArrayIndexOutOfBoundsException ex) { // catch the exception System.out.println(“Exception: “ + ex.getMessage( )); System.out.println("No matching element found."); } } // End of for loop } // End of main } // End of class ExcDemo4
  • 95. ITP 120 Java Programming I 95 Patrick Healy Class #14 – Exception Handling Using Multiple Catch Statements The output of the previous program ExcDemo4 is: 4 / 2 is 2 Can’t divide by Zero! 16 / 4 is 4 32 / 4 is 8 Can’t divide by Zero! 128 / 8 is 16 No matching element found. No matching element found.
  • 96. ITP 120 Java Programming I 96 Patrick Healy Class #14 – Exception Handling Catching SubClass Exceptions A catch clause for a superclass will also match any of its subclasses. For example, since the superclass of all exceptions is Throwable, to catch all possible exceptions, just catch Throwable ! If you want to catch exceptions of both a superclass type and a subclass type, put the subclass first in the catch sequence. Putting the superclass first causes unreachable code to be created since the subclass catch clause can never execute the code. In Java, unreachable code is an error !
  • 97. ITP 120 Java Programming I 97 Patrick Healy Class #14 – Exception Handling Catching SubClass Exceptions // Subclasses must precede superclasses in catch statements. class ExcDemo5 { public static void main(String[ ] args) { // Here, array number is longer than array denom. int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 }; for(int i=0; i<number.length; i++) { try { System.out.println(number[i] + " / " + denom[i] + " is " + number[i] / denom[i]); }
  • 98. ITP 120 Java Programming I 98 Patrick Healy Class #14 – Exception Handling Catching SubClass Exceptions catch (ArrayIndexOutOfBoundsException exc) // Subclass is first ! { System.out.println("No matching element found."); } catch (Throwable ex) // From superclass Throwable { System.out.println("Some type of exception occurred !"); // Could also add: System.out.println(“Exception: “ + ex.getMessage( ) + “ occurred”); } } // End of for loop } // End of main method } // End of class ExcDemo5
  • 99. ITP 120 Java Programming I 99 Patrick Healy Class #14 – Exception Handling Catching SubClass Exceptions Output from the program ExcDemo5: 4 / 2 is 2 Some exception occurred. 16 / 4 is 4 32 / 4 is 8 Some exception occurred. 128 / 8 is 16 No matching element found. No matching element found.
  • 100. ITP 120 Java Programming I 100 Patrick Healy Class #14 – Exception Handling Try Blocks can be Nested One try block can be nested within another. An exception generated within the inner try block that is NOT caught by a catch associated with that inner try is propagated to the outer try block. In the next program example, the ArrayIndexOutOfBoundsException is NOT caught by the inner try block, but it is caught by the outer try block.
  • 101. ITP 120 Java Programming I 101 Patrick Healy Class #14 – Exception Handling Try Blocks can be Nested // Use a nested try block. Catch error in outer block class NestTrys { public static void main(String[ ] args) { // Here, number array is longer than denom array int number[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; // 8 elements int denom[ ] = { 2, 0, 4, 4, 0, 8 }; // 6 elements try { // outer try for(int i=0; I < number.length; i++) { try { // nested try Start of inner try block System.out.println(number[i] + " / " + denom[i] + " is " + number[i] / denom[i]); } // End of inner try
  • 102. ITP 120 Java Programming I 102 Patrick Healy Class #14 – Exception Handling Try Blocks can be Nested catch (ArithmeticException ex) { System.out.println("Can't divide by Zero!"); // Catch the exception } } // End of for loop } // End of outer try catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println("No matching element found."); System.out.println("Fatal error -- program terminated."); } } // End of main method } // End of class NestTrys
  • 103. ITP 120 Java Programming I 103 Patrick Healy Class #14 – Exception Handling Try Blocks can be Nested In the previous program example, an exception that can be handled by the inner try, a divide-by-zero error, allows the program to continue. However, an array boundary error is caught by the outer try which causes the program to terminate. Output from the previous program example is: 4 / 2 is 2 Can’t divide by Zero! 16 / 4 is 4 32 / 4 is 8 Can’t divide by Zero! 128 / 8 is 16 No matching element found. Fatal error – program terminated. < --------- Note
  • 104. ITP 120 Java Programming I 104 Patrick Healy Class #14 – Exception Handling Throwing an Exception Manually The previous examples have been catching exceptions generated automatically by the Java Virtual Machine (JVM) However, it is possible to manually throw an exception by using the throw statement. The general form of the throw statement is: throw exceptOb; exceptOb must be an object of class Exception which is derived from class Throwable (which is derived from class Object)
  • 105. ITP 120 Java Programming I 105 Patrick Healy Class #14 – Exception Handling Throwing an Exception Manually // Manually throw an exception. class ThrowDemo { public static void main(String[ ] args) { try { System.out.println("Before throw."); throw new ArithmeticException( ); } catch (ArithmeticException exc) { // catch the exception System.out.println("Exception caught."); } System.out.println("After try/catch block."); } // End of main method } // End of class ThrowDemo
  • 106. ITP 120 Java Programming I 106 Patrick Healy Class #14 – Exception Handling Throwing an Exception Manually Output from the previous program ThrowDemo: Before throw. Exception caught. After try/catch block.
  • 107. ITP 120 Java Programming I 107 Patrick Healy Class #14 – Exception Handling Rethrowing an Exception An exception caught by one catch statement can be rethrown so that it can be caught by an outer catch statement. The reason for rethrowing an exception is to allow multiple handlers access to the exception. When you rethrow an exception, it will NOT be recaught by the same catch statement, but it will propagate to the next catch statement.
  • 108. ITP 120 Java Programming I 108 Patrick Healy Class #14 – Exception Handling Rethrowing an Exception // Rethrow an exception. class Rethrow { public static void genException( ) { // Note: array numer is longer than array denom int numer[ ] = { 4, 8, 16, 32, 64, 128, 256, 512 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 }; for(int i=0; i<numer.length; i++) { try { System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); }
  • 109. ITP 120 Java Programming I 109 Patrick Healy Class #14 – Exception Handling Rethrowing an Exception } catch (ArithmeticException exc) { // catch the exception System.out.println("Can't divide by Zero!"); } catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println("No matching element found."); throw exc; // Rethrow the exception ! } } }
  • 110. ITP 120 Java Programming I 110 Patrick Healy Class #14 – Exception Handling Rethrowing an Exception public class RethrowDemo { public static void main(String[ ] args) { try { Rethrow.genException(); // Class Rethrow, method genException() } catch (ArrayIndexOutOfBoundsException exc) { // recatch exception System.out.println("Fatal error: program terminated."); } } // End of main method } // End of class RethrowDemo
  • 111. ITP 120 Java Programming I 111 Patrick Healy Class #14 – Exception Handling Rethrowing an Exception In the previous program, divide-by-zero errors are handled locally by the genException( ) method, but an array boundary error is rethrown. The array boundary error is caught by the main( ) method Output from the program RethrowDemo.java: 4 / 2 is 2 Can’t divide by zero ! 16 / 4 is 4 32 / 4 is 8 Can’t divide by zero ! 128 / 8 is 16 No matching element found Fatal error – program terminated
  • 112. ITP 120 Java Programming I 112 Patrick Healy Class #14 – Exception Handling Using the keyword finally Sometimes you will want to define a block of code that will execute when the program leaves a try/catch block. For example, an exception might cause an error that terminates the current method, causing its premature return. However, that method may have opened a file or a network connection that needs to be closed. Java has a way to handle them: finally To specify that a block of code to execute when a try/catch block is exited, include a finally block at the end of the try/catch sequence.
  • 113. ITP 120 Java Programming I 113 Patrick Healy Class #14 – Exception Handling Using the keyword finally General form of a try/catch that includes finally: try { // Block of code to monitor for errors… } catch (ExcepType1 exObj1) { // Handler for ExceptionType1 } catch (ExcepType2 exObj2) { // Handler for ExceptionType2 } finally { // finally code goes here … }
  • 114. ITP 120 Java Programming I 114 Patrick Healy Class #14 – Exception Handling Using the keyword finally A try – catch block can be structured as try-catch-finally try { ………. } catch ( Exception ex ) { ………… } finally { ………… } finally indicates that after you finish handling the exception, perform these last actions. Or, even if the exception was not thrown or handled, perform the actions anyway.
  • 115. ITP 120 Java Programming I 115 Patrick Healy Class #14 – Exception Handling Using the keyword finally The finally block will be executed whenever execution leaves a try/catch block, no matter what conditions cause it. The last code to be executed is the code in the finally block
  • 116. ITP 120 Java Programming I 116 Patrick Healy Class #14 – Exception Handling Using the keyword finally public class UseFinally { // Use finally public static void genException(int num) { int t; int nums[ ] = new int[20]; // 20 numbers in array “nums” System.out.println("Receiving " + num ); try { switch(num) { case 0: t = 10 / num; // Generate divide-by-zero error (num is zero) break; case 1: nums[25] = 445; // Generate array index of out bounds error. break; case 2: return; // return from try block } } }
  • 117. ITP 120 Java Programming I 117 Patrick Healy Class #14 – Exception Handling Using the keyword finally catch (ArithmeticException exc) { // catch the exception System.out.println("Can't divide by Zero!"); return; // return from catch } catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println("No matching element found."); } finally { System.out.println(“In finally block Leaving try."); } } // End of method genException() } // End of class UseFinally
  • 118. ITP 120 Java Programming I 118 Patrick Healy Class #14 – Exception Handling Using the keyword finally Output from the previous program: UseFinally.java Receiving 0 Can’t divide by Zero! Leaving try. (message from finally block) Receiving 1 No matching element found. Leaving try. (message from finally block) Receiving 2 (merely return from try block) In finally block Leaving try. (message from finally block)
  • 119. ITP 120 Java Programming I 119 Patrick Healy Class #14 – Exception Handling Using Keyword throws In some cases, if a method generates an exception that is does not handle, it must declare the exception in a throws clause. The general form of a method that includes a throws clause is: return-type methodName(parameter list) throws exception-list { // body of the method here } Here, exception-list is a comma-separated list of exceptions that the method might throw outside of itself. Example: public void someMethod() throws Exception1, Exception2, Exception3
  • 120. ITP 120 Java Programming I 120 Patrick Healy Class #14 – Exception Handling Using Keyword throws In preceding examples, you did not need to specify a throws clause because exceptions that are subclasses of Error or RuntimeException do NOT need to be specified in a throws list. Java simply assumes that a method may throw one. All other types of exceptions must be declared. When performing keyboard input, you should add the clause: throws java.io.IOException to the main( ) method.
  • 121. ITP 120 Java Programming I 121 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions The usefulness of exceptions really stems from programs being able to report any type of problem encountered. Custom exceptions can be created by inheriting from any Exception class. For example we can create an exception to report insufficient funds when we try to withdraw too much money from an account.
  • 122. ITP 120 Java Programming I 122 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions Example 18.4 Insufficient Funds Exception (Custom Exception) public class InsufficientFundsException extends Exception( ) { public InsufficientFundsException( ) // Default constructor { super( “Insufficient funds to complete transaction” ); } public InsufficientFundsException( String message ) { super( message ); // Constructor with message parameter } }
  • 123. ITP 120 Java Programming I 123 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions Example 18.4 Continued // Account class public class Account { // include data members of Account class here // include constructors here // include other methods except withdraw which might throw exceptions // Next line of code: claiming an exception (throws) public void withDraw( double amount ) throws InsufficientFundsException( ) { // Next line of code: throwing an exception (throw) if ( amount > balance ) throw new InsufficientFundsException( ); else balance = balance – amount; } // End of method withDraw } // End of class Account
  • 124. ITP 120 Java Programming I 124 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions Note that the withdraw method of Account class in Example 18.4 has declared that it might throw an exception Note the difference between the keywords throw and throws Any call to the withdraw method must be enclosed in a try-catch block Because the caller must be ready to handle the exception if it is thrown.
  • 125. ITP 120 Java Programming I 125 Patrick Healy Class #14 – Exception Handling Refresher: throw & throws Claiming an Exception (“throws”) Every method must state the types of exceptions it can encounter. The term claiming an exception tells the compiler what can go wrong. public void someMethod( ) throws IOException Throwing an Exception (“throw”) When a program statement causes an error, the method containing he statement creates an exception object and passes it on to the system. The exception object contains information about the exception including the exception type and the state of the program when the error occurred. The Java code that handles the error is the exception handler.
  • 126. ITP 120 Java Programming I 126 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions Here is another example of a custom exception which is named NonIntResultException. NonIntResultException which is generated when the result of dividing two integer values produces a result with a fractional component. The method toString( ) is overridden which allows the description of the exception to be displayed using the println( ) method See the next slide 
  • 127. ITP 120 Java Programming I 127 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions // Create and use a custom exception. class NonIntResultException extends Exception { int n; int d; NonIntResultException(int i, int j) // Constructor with parameters { n = i; d = j; }
  • 128. ITP 120 Java Programming I 128 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions public String toString( ) { return "Result of " + n + " / " + d + " is non-integer."; } } // End of class NonIntResultException
  • 129. ITP 120 Java Programming I 129 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions class CustomExceptDemo { public static void main(String[ ] args) { // array numer has some odd values which yield non integer results // when dividing one integer by another. int numer [ ] = { 4, 8, 15, 32, 64, 127, 256, 512 }; int denom[ ] = { 2, 0, 4, 4, 0, 8 };
  • 130. ITP 120 Java Programming I 130 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions for(int i=0; I < numer.length; i++) { try { if( (numer[i] % 2) != 0) throw new NonIntResultException(numer[i], denom[i]); System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); }
  • 131. ITP 120 Java Programming I 131 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions catch (ArithmeticException exc) { // catch the exception System.out.println("Can't divide by Zero!"); } catch (ArrayIndexOutOfBoundsException exc) { // catch the exception System.out.println("No matching element found."); } catch (NonIntResultException ex) { System.out.println( “Exception: “ + ex.getMessage( )); } } // End of for loop } // End of main method } // End of class CustomExceptDemo
  • 132. ITP 120 Java Programming I 132 Patrick Healy Class #14 – Exception Handling Creating Custom Exceptions The output from the previous program is: 4 / 2 is 2 Can’t divide by Zero! Result of 15 / 4 is non-integer. 32 / 4 is 8 Can’t divide by Zero! Result of 127 / 8 is non-integer. No matching element found. No matching element found.
  • 133. Cautions When Using Exceptions ! Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. But, exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
  • 134. Assertions [ Optional ] The following section on Assertions is OPTIONAL
  • 135. Assertions [ Optional ] An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors.
  • 136. Declaring Assertions An assertion is declared using the new Java keyword assert in JDK 1.4 as follows: assert assertion; or assert assertion : detailMessage; where assertion is a Boolean expression and detailMessage is a primitive-type or an Object value.
  • 137. Executing Assertions When an assertion statement is executed, Java evaluates the assertion. If it is false, an AssertionError will be thrown. The AssertionError class has a no-arg constructor and seven overloaded single-argument constructors of type int, long, float, double, boolean, char, and Object. For the first assert statement with no detail message, the no-arg constructor of AssertionError is used. For the second assert statement with a detail message, an appropriate AssertionError constructor is used to match the data type of the message. Since AssertionError is a subclass of Error, when an assertion becomes false, the program displays a message on the console and exits.
  • 138. Executing Assertions Example public class AssertionDemo { public static void main(String[] args) { int i; int sum = 0; for (i = 0; i < 10; i++) { sum += i; } assert i == 10; assert sum > 10 && sum < 5 * 10 : "sum is " + sum; } }
  • 139. Compiling Programs with Assertions Since assert is a new Java keyword introduced in JDK 1.4, you have to compile the program using a JDK 1.4 compiler. Furthermore, you need to include the switch –source 1.4 in the compiler command as follows: javac –source 1.4 AssertionDemo.java NOTE: If you use JDK 1.5, there is no need to use the –source 1.4 option in the command.
  • 140. Running Programs with Assertions By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions, or –ea for short, as follows: java –ea AssertionDemo Assertions can be selectively enabled or disabled at class level or package level. The disable switch is – disableassertions or –da for short. For example, the following command enables assertions in package package1 and disables assertions in class Class1. java –ea:package1 –da:Class1 AssertionDemo
  • 141. Using Exception Handling or Assertions Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program. Exception handling addresses robustness and assertion addresses correctness. Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks. Assertions are checked at runtime and can be turned on or off at startup time.
  • 142. Using Exception Handling or Assertions, cont. Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. For example, the following code should be rewritten using exception handling as shown in Lines 28-35 in Circle.java in Listing 18.1. public void setRadius(double newRadius) { assert newRadius >= 0; radius = newRadius; }
  • 143. Using Exception Handling or Assertions, cont. Use assertions to reaffirm assumptions. This gives you more confidence to assure correctness of the program. A common use of assertions is to replace assumptions with assertions in the code.
  • 144. Using Exception Handling or Assertions, cont. Another good use of assertions is place assertions in a switch statement without a default case. For example, switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : "Invalid month: " + month }
  • 145. ITP 120 Java Programming I 145 Patrick Healy Class #14 – Exception Handling Chapter 17 Demo Programs Exceptions ExcDemo1.java ExcDemo3.java ExcDemo4.java ExcDemo5.java ExcTypeMismatch.java TestCircleWithException.java ExceptionScope.java goes with (CircleWithException.java) ExcCustomExceptDemo.java ExcDemoInfinity.java ExcNestedTrys.java ExcFinallyDemo.java ExcCreatingExceptions.java ExcChainedExceptionDemo.java ExcOutOfRangeException.java) (goes with ExcCreatingExceptions) ExcThrowDemo.java JamilGUICalculator.java ExcRethrow.java ExcProductCodes.java ExcNotHandled.java ExcCalculatorGUI.java
  • 146. ITP 120 Java Programming I 146 Patrick Healy Class #14 – Exception Handling End of Presentation
  翻译: