40
Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 1 C hapter13 How to handle exceptions

Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

  • View
    222

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 1

Chapter 13

How to handle exceptions

Page 2: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 2

Objectives

Applied

Given a method that throws one or more exceptions, code a method that calls that method and catches the exceptions.

Given a method that throws one or more exceptions, code a method that calls that method and throws the exceptions.

Code a method that throws an exception.

Use the methods of the Throwable class to get information about an exception.

Code a class that defines a new exception, and then use that exception in an application.

Use an assert statement in an application to make an assertion about a condition.

Page 3: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 3

Objectives (continued) Given Java code that uses any of the language elements presented

in this chapter, explain what each statement does.

Knowledge

Describe the Throwable hierarchy and the classes that are derived from it.

Describe the difference between checked and unchecked exceptions and explain when you need to catch each.

Explain how Java uses the stack trace to determine what exception handler to use when an exception occurs.

Describe the order in which you code the catch clauses in a try statement.

Explain what it means to swallow an exception.

Page 4: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 4

Objectives (continued) Explain when the code in the finally clause of a try statement is

executed and how that compares to code that follows a try statement.

Describe three situations where you might want to throw an exception from a method.

Describe two situations where you might create a custom exception class.

Explain what exception chaining is and when you might use it.

Explain what assertions are and how you can use them in your applications.

Page 5: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 5

The Throwable hierarchy

Throwable

Error Exception

Uncheckederrors

Uncheckedexceptions

Checkedexceptions

RuntimeException

Page 6: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 6

Common checked exceptions ClassNotFoundException IOException EOFException FileNotFoundException NoSuchMethodException

Common unchecked exceptions ArithmeticException IllegalArgumentException NumberFormatException IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException NullPointerException

Page 7: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 7

The exception hierarchy An exception is an object of the Exception class or any of its

subclasses. It represents a condition that prevents a method from successfully completing its function.

Checked exceptions are checked by the compiler. So you must supply code that handles any checked exceptions or your program won’t compile.

Unchecked exceptions are not checked by the compiler, but you can still write code that handles them. If you don’t, any unchecked exceptions will cause your program to terminate.

The Error class, like the Exception class, is derived from the Throwable class. However, the Error class identifies internal errors that are rare and can’t usually be recovered from.

Page 8: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 8

How Java propagates exceptions MethodA(){ try { MethodB(); } catch(ExceptionOne e) { // handle exception here }}

MethodB() throws ExceptionOne{ MethodC();}

MethodC() throws ExceptionOne{ MethodD();}

MethodD() throws ExceptionOne{ throw new ExceptionOne();}

Page 9: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 9

How to handle checked exceptions When a method encounters a condition it can’t handle, that

method should throw an exception. Then, users of the method can handle the exception in a way that’s right for their programs.

When a method calls another method that throws a checked exception, the method must either:

throw the exception up to its calling method, or

catch the exception and handle it

Code that catches an exception is known as an exception handler.

When an exception occurs, the runtime system looks for the appropriate exception handler.

To do that, it looks through the stack trace, or call stack, which lists the methods that have been called until it finds a method that catches the exception.

Page 10: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 10

The syntax of the try statement try { // statements that can cause an exception to be thrown } catch (MostSpecificExceptionType e) { // statements that handle the exception } catch (LeastSpecificExceptionType e) { // statements that handle the exception } finally { // statements that are executed whether or not // an exception is thrown }

Page 11: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 11

Code that uses a try statement in a loop to validate user input Scanner sc = new Scanner(System.in); // get the file name from the user RandomAccessFile file; String fileName; boolean validFileName = false; while (!validFileName) { System.out.print("File name: "); fileName = sc.next(); try { file = new RandomAccessFile(fileName, "r"); validFileName = true; } catch (FileNotFoundException e) { System.out.println("File not found."); } catch (IOException e) { System.out.println("An I/O error occurred."); } sc.nextLine(); } System.out.println("File name accepted.");

Page 12: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 12

How to use the try statement You use the catch clause of the try statement to catch specific

exception types.

You should code the catch clauses in sequence from the most specific class in the Throwable hierarchy to the least specific class.

A finally clause is executed whether or not an exception is thrown.

Page 13: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 13

A try statement that uses a finally clause try { // code that throws FileNotFoundException return productFile; } catch (FileNotFoundException e) { // code that handles FileNotFoundException return null; } finally { // code that's executed whether or not // FileNotFoundException is thrown }

Page 14: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 14

A try statement that doesn’t use a finally clause try { // code that throws FileNotFoundException } catch (FileNotFoundException e) { // code that handles FileNotFoundException } // code that's executed whether or not // FileNotFoundException is thrown

Page 15: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 15

A try statement that uses a finally clause for an unhandled exception

try { // code that throws FileNotFoundException // or IOException } catch (FileNotFoundException e) { // code that handles FileNotFoundException } finally { // code that's executed whether or not // FileNotFoundException or IOException is thrown } // code that's executed whether or not // FileNotFoundException is thrown // but not if IOException is thrown

Page 16: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 16

How to use the finally clause The code in the finally block is executed whether or not an

exception is thrown.

If the try statement is coded in a method that returns a value to its calling method, the code in the finally block is executed even if the code in the try block or a catch block issues a return statement.

Unlike the code in a finally block, code that follows a try statement isn’t executed if an exception is thrown but not handled by one of the catch clauses.

Page 17: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 17

The syntax for the declaration of a method that throws exceptions

modifiers returnType methodName([parameterList]) throws exceptionList {}

How to use the throws clause To throw a checked exception up to the calling method, you code

a throws clause in the method declaration.

The throws clause must name each checked exception that’s thrown up to the calling method.

Although you can specify unchecked exceptions in the throws clause, the compiler doesn’t force you to handle unchecked exceptions.

Page 18: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 18

A method that throws IOException public static long getFileLength() throws IOException { RandomAccessFile in = new RandomAccessFile("books.dat", "r"); long length = in.length(); return length; }

Page 19: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 19

A method that calls getFileLength and catches IOException

public static int getRecordCount() { try { long length = getFileLength(); // can throw IOException int recordCount = (int) (length / RECORD_SIZE); return recordCount; } catch (IOException e) { System.out.println("An IO error occurred."); return 0; } }

Page 20: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 20

Code that calls getFileLength without catching IOException

public static int getRecordCount() throws IOException { long length = getFileLength(); // can throw IOException int recordCount = (int) (length / RECORD_SIZE); return recordCount; }

Compiler error generated if you don’t catch or throw a checked exception

\java 1.5\examples\ch13\TestIOExceptionApp.java:26: unreported exception java.io.IOException; must be caught or declared to be thrown

Page 21: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 21

The syntax of the throw statement throw Throwable;

How to use the throw statement You use the throw statement to throw an exception.

You can name any object of type Throwable in a throw statement.

To throw a new exception, use the new keyword to call the constructor of the exception class you want to throw.

To throw an existing exception, you must first catch the exception with the catch clause of a try statement.

Page 22: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 22

A method that throws an unchecked exception public double calculateFutureValue(double monthlyPayment, double monthlyInterestRate, int months) { if (monthlyPayment <= 0) throw new IllegalArgumentException( "Monthly payment must be > 0"); if (monthlyInterestRate <= 0) throw new IllegalArgumentException( "Interest rate must be > 0"); if (months <= 0) throw new IllegalArgumentException( "Months must be > 0"); // code to calculate and return future value // goes here }

Page 23: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 23

Code that throws an IOException for testing purposes try { throw new IOException(); // must be the last statement // in the try block } catch (IOException e) { // code to handle IOException goes here }

Page 24: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 24

Code that rethrows an exception try { // code that throws IOException goes here } catch (IOException e) { System.out.println( "IOException thrown in getFileLength method."); throw e; }

Page 25: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 25

When to throw an exception When a method encounters a problem that prevents it from

completing its task, such as when the method is passed unacceptable argument values.

When you want to generate an exception to test an exception handler.

When you want to catch an exception, perform some processing, then throw the exception again so it can be handled by the calling method.

Page 26: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 26

Common constructors of the Throwable class

Constructor Description

Throwable() Creates a new exception with a null message.

Throwable(message) Creates a new exception with the specified message.

Page 27: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 27

Common methods of the Throwable class

Method Description

getMessage() Returns the message associated with the exception, if one is available.

printStackTrace() Prints the stack trace to the standard error output stream along with the value of the toString method of the exception object.

toString() Returns a string that includes the name of the class that the exception was created from, along with the message associated with the exception, if one is available.

Page 28: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 28

Code that throws an exception with a message try { throw new IOException("An IO error has occurred."); } catch (IOException e) { System.err.println(e.getMessage()); System.err.println(e.toString()); }

Resulting output An IO error has occurred. java.io.IOException: An IO error has occurred.

Page 29: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 29

Code that uses the printStackTrace method try { throw new IOException("An IO error has occurred."); } catch (IOException e) { e.printStackTrace(); } }

Resulting output java.io.IOException: An IO error has occurred. at ProductTestApp.getProductData(ProductTestApp.java:14) at ProductTestApp.main(ProductTestApp.java:7)

Page 30: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 30

How to create your own exception class To define a checked exception, inherit the Exception class or any

of its subclasses.

To define an unchecked exception, inherit the RuntimeException class or any of its subclasses.

By convention, each exception class should contain a default constructor that doesn’t accept any arguments and another constructor that accepts a string argument.

When to define your own exceptions When a method requires an exception that isn’t provided by any

of Java’s exception types

When using a built-in Java exception would inappropriately expose details of a method’s operation

Page 31: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 31

Code for a user-defined exception class public class ProductDAOException extends Exception { public ProductDAOException() { } public ProductDAOException(String message) { super(message); } }

Page 32: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 32

A method that throws the ProductDAOException public static Product getProduct(String productCode) throws ProductDAOException { try { Product p = readProduct(productCode); // may throw IOException return p; } catch (IOException e) { throw new ProductDAOException("An IO error occurred while retrieving the product."); } }

Page 33: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 33

Code that catches the ProductDAOException try { Product p = getProduct("1234"); } catch (ProductDAOException e) { System.out.println(e.getmessage()); }

Page 34: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 34

Constructors and methods of the Throwable class for exception chaining

Constructor Description

Throwable(cause) Creates a new exception with the specified exception object as its cause.

Throwable(message, cause) Creates a new exception with the specified message and cause.

Method Description

getCause() Returns the exception object that represents this exception’s cause.

initCause(cause) Sets the exception’s cause to the specified exception. Can be called only once. If you initialize the cause via the constructor, you can’t call this method at all.

Page 35: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 35

How to use exception chaining Exception chaining lets you maintain exception information for

exceptions that are caught when new exceptions are thrown.

Exception chaining uses the cause field, which represents the original exception that caused the current exception to be thrown.

You can set the cause of an exception via the exception’s constructor or by using the initCause method.

You can retrieve an exception’s cause by using the getCause method.

Page 36: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 36

A custom exception class that uses exception chaining public class ProductDAOException extends Exception { public ProductDAOException() { } public ProductDAOException(Throwable cause) { super(cause); } }

Code that throws ProductDAOException with chaining catch (IOException e) { throw new ProductDAOException(e); }

Page 37: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 37

Code that catches ProductDAOException and displays the cause catch (ProductDAOException e) { System.out.println( "A ProductDAOException has occurred."); System.out.println(e.getCause().toString()); }

Resulting output A ProductDAOException has occurred. java.io.IOException: IOException

Page 38: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 38

The syntax of the assert statement assert booleanExpression [: message ];

Code that makes a reasonable assertion about a calculation for (int i = 1; i <= months; i++) { futureValue = (futureValue + monthlyInvestment) * monthlyInterestRate; } // future value should be at least monthlyInterest * months assert (futureValue > monthlyInvestment * months) : "FV out of range";

The output that’s displayed when an assertion exception is thrown Exception in thread "main" java.lang.AssertionError: FV out of range at FutureValueApp.calculateFutureValue(FutureValueApp.java:152) at FutureValueApp.main(FutureValueApp.java:42)

Page 39: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 39

TextPad’s Preferences dialog box with the –ea switch set

Page 40: Murach’s Beg. Java 2, JDK 5, C13© 2005, Mike Murach & Associates, Inc.Slide 1

Murach’s Beg. Java 2, JDK 5, C13 © 2005, Mike Murach & Associates, Inc. Slide 40

How to work with assertions You can use an assert statement to code an assertion, which is a

condition that should be true at a given point in your application.

Assertions are disabled by default. To enable assertions:

From the command prompt: Enter the –ea switch after the java command for the application.

From TextPad: Choose ConfigurePreferences, expand the Tools group, select the Run Java Application option, and add –ea at the beginning of the Parameters text box.

If assertions are enabled, the JRE evaluates assert statements and throws an AssertionError if the specified condition is false. If a message is coded in the assert statement, it’s included in the AssertionError.

An assert statement shouldn’t include any code that performs a task. If it does, the program will run differently depending on whether assertions are enabled or disabled.