Download - Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

Transcript
Page 1: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

Chapter 12Chapter 12Chapter 12Chapter 12

ByByTony GaddisTony Gaddis

Modified byModified by

Elizabeth AdamsElizabeth Adams

Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

Page 2: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

2

Chapter TopicsToday

– Exceptions– Handling Exceptions– Throwing Exceptions

Thursday• More about Input/Output Streams• Advanced Topics:

– Binary Files, – Random Access Files, and – Object Serialization

Page 3: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

3

Exceptions

• An exception is an object that is generated as the result of an error or an unexpected event.

• Unhandled exceptions cause programs to bomb.

• This is not a good thing, particularly if the program is flying a plane or administering radiation, or running a nuclear reactor.

• Exceptions are runtime errors.

Page 4: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

4

Handling Exceptions• In Java, exceptions are said to have been

“thrown.” In other languages, they may be “raised.”

• It is the programmers responsibility to write code that anticipates the occurrence of an exception and keeps the program from crashing.

• The code that does this is said to “handle” the exception and is called an exception handler.

• If the programmer doesn’t write code to “handle the exception”, the default exception handler does. It prints an error message and crashes the program which isn’t very satisfactory.

Page 5: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

5

Exception ClassesObject

Throwable

ExceptionError

RuntimeExceptionIOException

FileNotFoundExceptionEOFException

Page 6: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

6

Handling Exceptions• To handle an exception, you use a try catch

block try{ (try block statements...)}catch (ExceptionType ParameterName){ (catch block statements...)}

• try indicates the code that might cause an exception to occur

• catch indicates the exception that you expect to catch and how you want to handle it.

Page 7: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

7

Catch Blocks• A catch clause begins with the key word

catch and has a parameter list consisting of the type of the exception and a variable name.

catch (ExceptionType ParameterName)

• The code between the required curly braces following the catch clause will be executed if the try block throws the referenced exception.

• The Java Virtual Machine searches for a catch clause that can deal with the exception

.

Page 8: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

8

Handling Exceptions• Each exception object has a

method named getMessage that can be used to retrieve the default error message for the exception.

• Example: – ExceptionMessage.java

Page 9: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

9

Handling Exceptions• The parameter must be of a type

that is compatible with the thrown exception’s type.

• After an exception is handled, the program will leave the catch block and continue execution at the point following it.

Page 10: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

10

Polymorphic References To Exceptions

• When handling exceptions, you can use a polymorphic reference as a parameter in the catch clause but do not do so in this course.

• The exceptions that you must handle are the checked exceptions . They are derived from the Exception class.

• There are unchecked exceptions derived from RuntimeException which can be ignored but you should not ignore them in this course.

• A catch clause that uses a parameter variable of the Exception type is capable of catching any exception that is derived from the Exception class.

Page 11: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

11

Handling Multiple Exceptions

• The code in the try block may be capable of throwing more than one type of exception.

• A catch clause needs to be written for each type of exception that could potentially be thrown.

• The JVM will run the first compatible catch clause found.

Page 12: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

12

Exception Handlers• A try statement may have only one catch

clause for each specific type of exception.try{ number = Integer.parseInt(str);}catch (NumberFormatException e){ System.out.println("Bad number format.");}catch (NumberFormatException e) // ERROR!!!{ System.out.println(str + " is not a number.");}

Page 13: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

13

Exception Handlers• The NumberFormatException class is

derived from the IllegalArgumentException class.try{ number = Integer.parseInt(str);}catch (IllegalArgumentException e){ System.out.println("Bad number format.");}

catch (NumberFormatException e) // ERROR!!!{ System.out.println(str + " is not a number.");}

Page 14: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

14

The finally Clause• The try statement may have an optional

finally clause.• If present, the finally clause must appear

after all of the catch clauses.try{ (try block statements...)}catch (ExceptionType ParameterName){ (catch block statements...)}finally{ (finally block statements...)}

Page 15: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

15

The finally Clause• The finally block is one or more

statements,– that are always executed after the try block

has executed and– that are always executed after any catch

blocks have executed if an exception was thrown.

• The statements in the finally block execute whether an exception occurs or not.

Page 16: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

16

The Stack Trace• The call stack is an internal list of all the

methods that are currently executing.• A stack trace is a list of all the methods

in the call stack. • It indicates:

– the method that was executing when an exception occurred and

– all of the methods that were called in order to execute that method.

Page 17: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

17

Uncaught Exceptions

• When an exception is thrown, it cannot be ignored.

• It must be handled by the program, or by the default exception handler.

• When the code in a method throws an exception:– normal execution of that method stops – the JVM searches for a compatible

exception handler inside the method.

Page 18: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

18

Uncaught Exceptions• If there is no exception handler inside

the method:– control of the program is passed to the

previous method in the call stack.– If that method has no exception handler,

then control is passed again, up the call stack, to the previous method.

• If control reaches the main method:– the main method must either handle the

exception, or– the program is halted and the default

exception handler handles the exception.

Page 19: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

19

Checked and Unchecked Exceptions

• There are two categories of exceptions:– Unchecked– Checked.

• Unchecked exceptions derived from Error, which are thrown when a critical error occurs, should not be handled.

• Unchecked exceptions derived from RuntimeException should be handled or prevented.

• Checked exceptions derived from Exception do have to be handled by you.

Page 20: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

20

Checked and Unchecked Exceptions

• If the code in a method can throw a checked exception, the method:– must handle the exception, or– it must have a throws clause listed in the

method header.

• The throws clause informs the compiler what exceptions can be thrown from a method and avoids a compile time error

Page 21: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

23

Throwing Exceptions• You can write code that:

– throws one of the standard Java exceptions, or

– an instance of a custom exception class that you have designed.

• The throw statement is used to manually throw an exception.throw new ExceptionType(MessageString);

• The throw statement causes an exception object to be created and thrown.

Page 22: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

24

Throwing Exceptions• The MessageString argument contains a

custom error message that can be retrieved from the exception object’s getMessage method.

• If you do not pass a message to the constructor, the exception will have a null message.throw new Exception("Out of fuel");

– Note: Don’t confuse the throw statement with the throws clause.

• Example in text: DateComponentExceptionDemo.java

Page 23: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

25

Creating Exception Classes

• You can create your own exception classes by deriving them from the Exception class or one of its derived classes.

• Example:– BankAccount.java– NegativeStartingBalance.java– AccountTest.java

Page 24: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

26

Creating Exception Classes

• Some examples of exceptions that can affect a bank account: These should be handled by program not as exceptions.– A negative starting balance is passed to the constructor.– A negative interest rate is passed to the constructor.– A negative number is passed to the deposit method.– A negative number is passed to the withdraw method.– The amount passed to the withdraw method exceeds the

account’s balance.

• We can create exceptions that represent each of these error conditions but that would be stupid.

Page 25: Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

27

@exception Tag in Documentation Comments• General format

@exception ExceptionName Description

• Remember:@param@result@author