Top Banner
Chapter 18 Chapter 18 Exceptions & Assertions Exceptions & Assertions Java I ITP 120 Java I ITP 120
146

Itp 120 Chapt 18 2009 Exceptions & Assertions

Sep 05, 2014

Download

Documents

phanleson

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Itp 120 Chapt 18 2009 Exceptions & Assertions

Chapter 18 Chapter 18 Exceptions & Assertions Exceptions & Assertions

Java I ITP 120Java I ITP 120

Page 2: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 2Patrick 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

Page 3: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 3Patrick 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.

Page 4: Itp 120 Chapt 18 2009 Exceptions & Assertions

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

Page 5: Itp 120 Chapt 18 2009 Exceptions & Assertions

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

Page 6: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 6Patrick Healy

Class #14 – Exception Handling Catching 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.

Page 7: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 7Patrick 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.

Page 8: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 8Patrick Healy

Class #14 – Exception Handling Exception Handling : Examples of Problems Examples 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)

Page 9: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 9Patrick 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.

Page 10: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 10Patrick 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.

Page 11: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 11Patrick 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.

Page 12: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 12Patrick Healy

Class #14 – Exception Handling Exceptions and Exception Types

Page 13: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 13Patrick Healy

Class #14 – Exception Handling System 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.

Page 14: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 14Patrick Healy

Class #14 – Exception Handling Exceptions (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.

Page 15: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 15Patrick Healy

Class #14 – Exception Handling Runtime 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.

Page 16: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 16Patrick Healy

Class #14 – Exception Handling Java’s Built-in UnChecked ExceptionsException Meaning

ArithmeticException Arithmetic error; divide-by-zeroArrayIndexOutOfBoundsException Array index is out of boundsArrayStoreException Assignment of an array element

is an incompatible type.ClassCastException Invalid cast operationIllegalArgumentException Illegal argument used to invoke a

methodIndexOutOfBoundsException Some type of index is out of

bounds

Page 17: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 17Patrick Healy

Class #14 – Exception Handling Java’s Built-in UnChecked ExceptionsException Meaning

NegativeArraySizeException Array created with a negative sizeNullPointerException Invalid use of a null referenceNumberFormatException Invalid conversion of a string to a

numeric formatStringIndexOutOfBounds Attempt to index outside the bounds of a

string

Page 18: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 18Patrick Healy

Class #14 – Exception Handling Java’s Built-in Checked ExceptionsException Meaning

ClassNotFoundException Class not found.CloneNotSupportedException Attempt to clone an object that

does not implement the Cloneable interface

IllegalAccessException Access to a class is deniedInstantiation Exception Attempt to create an object of an

abstract class or interface.InterruptedException One thread has been interrupted

by another threadNoSuchMethodException Method does not exist

Page 19: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 20: Itp 120 Chapt 18 2009 Exceptions & Assertions

Unchecked ExceptionsIn 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.

Page 21: Itp 120 Chapt 18 2009 Exceptions & Assertions

Declaring ExceptionsEvery 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

Page 22: Itp 120 Chapt 18 2009 Exceptions & Assertions

Throwing ExceptionsWhen 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;

Page 23: Itp 120 Chapt 18 2009 Exceptions & Assertions

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"); }

Page 24: Itp 120 Chapt 18 2009 Exceptions & Assertions

Catching Exceptionstry { statements; // Statements that may throw exceptions}catch (Exception1 exVar1) { handler for exception1;}catch (Exception2 exVar2) { handler for exception2;}...catch (ExceptionN exVar3) { handler for exceptionN;}

Page 25: Itp 120 Chapt 18 2009 Exceptions & Assertions

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

Page 26: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 26Patrick 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 tomethod3.If the exception type is Exception3, it is caught by the catch clause for

handling ex3 in Method 2If the exception type is Exception2, it is caught by the catch clause for

handling ex2 in Method 1If 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.

Page 27: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 27Patrick 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 areskipped.

If the exception type is Exception1, then statements 1,3 & 5 are skipped.

Page 28: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 28Patrick 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.

Page 29: Itp 120 Chapt 18 2009 Exceptions & Assertions

Catch or Declare Checked ExceptionsJava 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(); }

Page 30: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

try { statements;}catch(TheException ex) {

handling ex; }finally { finalStatements; }

Next statement;

Suppose no exceptions in the statements

Page 31: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

try { statements;}catch(TheException ex) {

handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed

Page 32: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace Executionanimationtry { statements;}catch(TheException ex) {

handling ex; }finally { finalStatements; }

Next statement;

Next statement in the method is executed

Page 33: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

Suppose an exception of type Exception1 is thrown in statement2

Page 34: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The exception is handled here

Page 35: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The final block statements are always executed.

Page 36: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

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.

Page 37: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

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.

Page 38: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }

Next statement;

Handle the exception

Page 39: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

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

Page 40: Itp 120 Chapt 18 2009 Exceptions & Assertions

Trace a Program Executionanimation

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

Page 41: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 41Patrick 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.

Page 42: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 42Patrick 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.

Page 43: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 43Patrick Healy

Class #14 – Exception Handling The JVM handles a Divide Exception !

// ExcDemoInfinity.javaimport 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

Page 44: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 44Patrick 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.

Page 45: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 45Patrick 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( );

Page 46: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 46Patrick 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;

Page 47: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 47Patrick 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

Page 48: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 48Patrick 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

Page 49: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 49Patrick 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

Page 50: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 50Patrick 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

Page 51: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 51Patrick 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.

Page 52: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 52Patrick 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.

Page 53: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 53Patrick 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.

Page 54: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 54Patrick 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 achecked 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.

Page 55: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 55Patrick 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.

Page 56: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 56Patrick Healy

Class #14 – Exception Handling Java’s Built-in UnChecked ExceptionsException Meaning

ArithmeticException Arithmetic error; divide-by-zeroArrayIndexOutOfBoundsException Array index is out of boundsArrayStoreException Assignment of an array element

is an incompatible type.ClassCastException Invalid cast operationIllegalArgumentException Illegal argument used to invoke a

methodIndexOutOfBoundsException Some type of index is out of

bounds

Page 57: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 57Patrick Healy

Class #14 – Exception Handling Java’s Built-in UnChecked ExceptionsException Meaning

NegativeArraySizeException Array created with a negative sizeNullPointerException Invalid use of a null referenceNumberFormatException Invalid conversion of a string to a

numeric formatStringIndexOutOfBounds Attempt to index outside the bounds of a

string

Page 58: Itp 120 Chapt 18 2009 Exceptions & Assertions

Exceptions in GUI ApplicationsThe 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.

Page 59: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 60: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 60Patrick Healy

Class #14 – Exception Handling Exceptions thrown by methods of class IntegerRemember: 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);

Page 61: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 61Patrick Healy

Class #14 – Exception Handling Java’s Built-in Checked ExceptionsException Meaning

ClassNotFoundException Class not found.CloneNotSupportedException Attempt to clone an object that

does not implement the Cloneable interface

IllegalAccessException Access to a class is deniedInstantiation Exception Attempt to create an object of an

abstract class or interface.InterruptedException One thread has been interrupted

by another threadNoSuchMethodException Method does not exist

Page 62: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 62Patrick 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.

Page 63: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 63Patrick 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 )

Page 64: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 64Patrick Healy

Class #14 – Exception Handling Handling Exceptions within a ProgramThe 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

Page 65: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 65Patrick 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 }

Page 66: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 66Patrick 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.

Page 67: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 67Patrick 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.

Page 68: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 68Patrick 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( ) );}

Page 69: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 69Patrick 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

Page 70: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 70Patrick 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

Page 71: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 71Patrick 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

Page 72: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 72Patrick 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

Page 73: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 73Patrick 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 exceptionExample:

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

Page 74: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 74Patrick 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 wrongthrow new IOException();

} A method can throw more than one exception since any number of

things can go wrong.

Page 75: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 75Patrick 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}

Page 76: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 76Patrick 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.}

}

Page 77: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 77Patrick 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() ); }}

}

Page 78: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 78Patrick 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() ); }}

}

Page 79: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 79Patrick 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}

Page 80: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 80Patrick 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.

Page 81: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 81Patrick Healy

Class #14 – Exception Handling A Simple Exception Exampleclass 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

Page 82: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 82Patrick Healy

Class #14 – Exception Handling A Simple Exception example (continued)Output from running Java program ExcDemo1

Before exception is generated.Error from Java: nullIndex out-of-bounds!After catch statement.

Page 83: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 83Patrick 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

Page 84: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 84Patrick 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

Page 85: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 85Patrick 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.

Page 86: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 86Patrick 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

Page 87: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 87Patrick 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)

Page 88: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 88Patrick 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.

Page 89: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 89Patrick 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"); }

Page 90: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 90Patrick 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

Page 91: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 91Patrick 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

Page 92: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 92Patrick 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.

Page 93: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 93Patrick 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]); }

Page 94: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 94Patrick 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

Page 95: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 95Patrick Healy

Class #14 – Exception Handling Using Multiple Catch Statements The output of the previous program ExcDemo4 is:4 / 2 is 2Can’t divide by Zero!16 / 4 is 432 / 4 is 8Can’t divide by Zero!128 / 8 is 16No matching element found.No matching element found.

Page 96: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 96Patrick 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 !

Page 97: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 97Patrick 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]); }

Page 98: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 98Patrick 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

Page 99: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 99Patrick Healy

Class #14 – Exception Handling Catching SubClass ExceptionsOutput from the program ExcDemo5:4 / 2 is 2Some exception occurred.16 / 4 is 432 / 4 is 8Some exception occurred.128 / 8 is 16No matching element found.No matching element found.

Page 100: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 100Patrick 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.

Page 101: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 101Patrick Healy

Class #14 – Exception Handling Try Blocks can be Nested// Use a nested try block. Catch error in outer blockclass 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

Page 102: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 102Patrick Healy

Class #14 – Exception Handling Try Blocks can be Nestedcatch (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

Page 103: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 103Patrick 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 2Can’t divide by Zero!16 / 4 is 432 / 4 is 8Can’t divide by Zero!128 / 8 is 16No matching element found.Fatal error – program terminated. < --------- Note

Page 104: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 104Patrick 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)

Page 105: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 105Patrick 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

Page 106: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 106Patrick Healy

Class #14 – Exception Handling Throwing an Exception Manually Output from the previous program ThrowDemo: Before throw. Exception caught. After try/catch block.

Page 107: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 107Patrick 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.

Page 108: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 108Patrick 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]); }

Page 109: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 109Patrick 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 ! } } }

Page 110: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 110Patrick Healy

Class #14 – Exception Handling Rethrowing an Exceptionpublic 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

Page 111: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 111Patrick 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

Page 112: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 112Patrick 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.

Page 113: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 113Patrick 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 … }

Page 114: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 114Patrick 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.

Page 115: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 115Patrick 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

Page 116: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 116Patrick Healy

Class #14 – Exception Handling Using the keyword finallypublic 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 } } }

Page 117: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 117Patrick Healy

Class #14 – Exception Handling Using the keyword finallycatch (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

Page 118: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 118Patrick Healy

Class #14 – Exception Handling Using the keyword finally Output from the previous program: UseFinally.javaReceiving 0Can’t divide by Zero!Leaving try. (message from finally block)

Receiving 1No 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)

Page 119: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 119Patrick 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

Page 120: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 120Patrick 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.

Page 121: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 121Patrick 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.

Page 122: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 122Patrick 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 }}

Page 123: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 123Patrick Healy

Class #14 – Exception Handling Creating Custom Exceptions Example 18.4 Continued

// Account classpublic 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

Page 124: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 124Patrick 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.

Page 125: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 125Patrick 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.

Page 126: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 126Patrick 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

Page 127: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 127Patrick 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; }

Page 128: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 128Patrick Healy

Class #14 – Exception Handling Creating Custom Exceptionspublic String toString( ) { return "Result of " + n + " / " + d + " is non-integer."; } } // End of class NonIntResultException

Page 129: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 129Patrick Healy

Class #14 – Exception Handling Creating Custom Exceptionsclass 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 };

Page 130: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 130Patrick 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]); }

Page 131: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 131Patrick 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

Page 132: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 132Patrick Healy

Class #14 – Exception Handling Creating Custom ExceptionsThe output from the previous program is:4 / 2 is 2Can’t divide by Zero!Result of 15 / 4 is non-integer.32 / 4 is 8Can’t divide by Zero!Result of 127 / 8 is non-integer.No matching element found.No matching element found.

Page 133: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 134: Itp 120 Chapt 18 2009 Exceptions & Assertions

Assertions [ Optional ]

The following section on Assertions is OPTIONAL

Page 135: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 136: Itp 120 Chapt 18 2009 Exceptions & Assertions

Declaring AssertionsAn assertion is declared using the new Java keyword assert in JDK 1.4 as follows:

assert assertion; orassert assertion : detailMessage;

where assertion is a Boolean expression and detailMessage is a primitive-type or an Object value.

Page 137: Itp 120 Chapt 18 2009 Exceptions & Assertions

Executing AssertionsWhen 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.

Page 138: Itp 120 Chapt 18 2009 Exceptions & Assertions

Executing Assertions Examplepublic 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; }}

Page 139: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 140: Itp 120 Chapt 18 2009 Exceptions & Assertions

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

Page 141: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 142: Itp 120 Chapt 18 2009 Exceptions & Assertions

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;}

Page 143: Itp 120 Chapt 18 2009 Exceptions & Assertions

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.

Page 144: Itp 120 Chapt 18 2009 Exceptions & Assertions

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}

Page 145: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 145Patrick Healy

Class #14 – Exception Handling Chapter 17 Demo Programs ExceptionsExcDemo1.java ExcDemo3.javaExcDemo4.java ExcDemo5.java ExcTypeMismatch.java TestCircleWithException.javaExceptionScope.java goes with (CircleWithException.java)ExcCustomExceptDemo.java ExcDemoInfinity.javaExcNestedTrys.java ExcFinallyDemo.javaExcCreatingExceptions.java ExcChainedExceptionDemo.java ExcOutOfRangeException.java) (goes with ExcCreatingExceptions)ExcThrowDemo.java JamilGUICalculator.javaExcRethrow.java ExcProductCodes.javaExcNotHandled.java ExcCalculatorGUI.java

Page 146: Itp 120 Chapt 18 2009 Exceptions & Assertions

ITP 120 Java Programming I 146Patrick Healy

Class #14 – Exception Handling End of Presentation