chapter 81 exception handling chapter 8. 2 objectives become familiar with the notion of exception...

52
Chapter 8 1 Exception Handling Chapter 8

Upload: samantha-holland

Post on 26-Dec-2015

227 views

Category:

Documents


1 download

TRANSCRIPT

Chapter 8 1

Exception Handling

Chapter 8

Chapter 8 4

Introduction

• A program can be written assuming that nothing unusual or incorrect will happen.– The user will always enter an integer when

prompted to do so. – There will always be a nonempty list for a

program that takes an entry from the list.– The file containing the needed information

will always exist.• Unfortunately, it isn’t always so.

Chapter 8 5

Introduction, cont.

• Once the core program is written for the usual, expected case(s), Java’s exception-handling facilities should be added to accommodate the unusual, unexpected case(s).

Chapter 8 6

Introduction, cont.

• Exception handling divides a class or method definition into separate sections:– one section for the normal case(s)– another section for the exceptional case(s).

• Depending on how a method is used, special cases may need to be handled in different ways.

• Sometimes an exception needs to be thrown to handle a problem outside the method.

Chapter 8 8

Exception Handling

• Either your code or Java signals when something unusual happens.

• The signaling process is called throwing an exception.

• Somewhere in your program, you can place code to handle the exception.

Chapter 8 9

Exceptions in Java: Example

• simple example– Suppose the students are hosting an event

to express appreciation to their professor, at which donuts and milk will be served.

– If the number of donuts is known, and the number of glasses of milk is known, it should be possible to calculate the number of donuts per glass of milk.

Chapter 8 10

Exceptions in Java: Example, cont.

• simple example, cont.– But what if there is no milk?– An attempt to divide the number of donuts

by the number of glasses of milk will result in an attempt to divide by zero.

– This would be an utter (udder?) disaster, known in Java as an exception.

Chapter 8 11

Exceptions in Java: Example, cont.

• In Java, it is possible to test for this unusual situation using an if-else statement, for example.

Chapter 8 12

Exceptions in Java: Example, cont.

• class GotMilk

Chapter 8 14

Exceptions in Java: Example, cont.

• In Java, it is also possible to throw an exception.

Chapter 8 15

Exceptions in Java: Example, cont.

• class ExceptionDemo

Chapter 8 18

Exceptions in Java

• Exceptions are handled using a try-throw-catch threesome.

• try block syntaxtry

{

Code_to_Try

Throw_An_Exception_Or_Invoke_A_Method _That_Might_Throw_An_Exception

Possibly_More_Code

}

Chapter 8 19

Exceptions in Java, cont.

• Exception is a predefined class.• The throw statement creates a new object of

the class Exception and throws it.throw new Exception

(“Exception: No Milk!”);

• When an exception is thrown, control transfers from the try block to a catch block, and is called catching the exception.

Chapter 8 20

throw Statement and catch Block

• throw statement syntaxthrow new Exception_Class_Name

(Quoted_String_Argument);

– Quoted_String_Argument is passed to the constructor for class Exception which stores it in the instance variable of the Exception object.

Chapter 8 21

throw Statement and catch Block, cont.

• catch block syntaxcatch(Exception e)

{

Code_To_Be_Performed

{

– e is called the catch-block parameter.

Chapter 8 22

The catch Block

• The class name preceding the catch-block parameter specifies what kind of exception the catch block can catch.– Class name Exception permits any

exception to be caught.• The catch-block parameter provides a name

for the exception that is caught, to permit the exception object to be used subsequently.

Chapter 8 23

The catch Block, cont.

• If the program cannot recover from the exception, the catch block can includeSystem.exit(0);

Chapter 8 24

method getMessage

• Every exception has a method called getMessage.

• By default, this method retrieves the string given to the constructor of the Exception object.

Chapter 8 25

method getMessage, cont.• class ExceptionDemo Flow of Control - no

exception is thrown

Chapter 8 26

method getMessage, cont.• class ExceptionDemo Flow of Control - an

exception is thrown

Chapter 8 27

try-throw-catch

• The try-throw-catch threesome is similar to an if-else statement.

• However, an object of the class Exception is created and its message can be carried by the thrown exception, providing more versatility than an if-else statement

Chapter 8 28

Predefined Exception Classes

• Some methods in predefined classes can throw predefined exceptions.

• An invocation of such a predefined method can be included in a try block and followed by a catch block.

• some predefined exceptions:– IOException– ClassNotFoundException– FileNotFoundException

Chapter 8 29

Predefined Exception Classes, cont.

• Class Exception is the root class of all exceptions.

• However, an exception typically is handled more appropriately by one of its descendants.

• The string returned by a predefined exception typically provides enough information to identify the reason for the exception.

Chapter 8 30

ArrayOutOfBoundsException

• When a program attempts to use an array index that is out of bounds, an ArrayOutOfBoundsException is thrown.

• The program ends unless the exception is caught in a catch block.

• An ArrayOutOfBoundsException usually indicates a code error rather than an exception that should be caught.

Chapter 8 31

Defining Exception Classes

• You can define your own exception classes, but they must be derived from an existing exception class.

• Constructors are the most important, and often the only methods (except for methods inherited from the base class).

Chapter 8 32

Defining Exception Classes, cont.

• class DivideByZeroException

Chapter 8 33

Defining Exception Classes, cont.

• class DivideByZeroExceptionDemo

Chapter 8 37

Java Tip: Preserve getMessage

• For all predefined exception classes, method getMessage returns either– the string that is passed as an argument to

the constructor or– a default string if no argument is passed to

the constructor.• The behavior of method getMessage should be

preserved in any exception class you define.

Chapter 8 38

Java Tip: Preserve getMessage, cont.

• This is done by including a string parameter that begins with a call to super.public MyException(String message)

{

super(message);

More_Code_If_Appropriate

}

Chapter 8 39

Java Tip: Preserve getMessage, cont.

• Also include a default constructor.public MyException()

{

super(“MyException thrown”);

More_Code_If_Appropriate

}

Chapter 8 40

Programming Tip: When to Define an Exception Class

• In general, define an exception class if you are going to insert a throw statement in your code.

• This permits catch blocks to distinguish between your exceptions and exceptions thrown by predefined methods.

Chapter 8 41

Guidelines

• Use class Exception as the base class unless there is a compelling reason to do otherwise.

• Define at least two constructors. Typically, no other methods are needed.

• Begin each constructor definition with a call to the constructor of the base class.

Chapter 8 44

Declaring Exceptions (Passing the Buck)

• Sometimes is it appropriate to handle an exception other than in the method where the exception occurred.

• For example, it might be better to handle the exception in the method that called the method that called the method… that threw the exception

Chapter 8 45

Declaring Exceptions, cont.

• If a method can throw an exception but does not catch it, it must alert the programmer to the possibility of an exception by including a throws clause.

• Examplepublic void someMethod()

throws DivideByZeroException

Chapter 8 46

Accounting for Exceptions

• An exception can be caught in a catch block within a method definition.

• Alternatively, the possibility of an exception can be declared at the start of the method definition by placing the exception-class name in a throws clause.

• These two approaches can be mixed in a method, catching some exceptions and declaring others in a throws clause.

Chapter 8 47

Accounting for Exceptions, cont.

• If method_A uses a throws clause instead of handling an exception and method_B calls method_A, then method_B either must handle the exception or must also include a throws clause.

Chapter 8 48

Accounting for Exceptions, cont.

• class DoDivision

Chapter 8 49

Accounting for Exceptions, cont.

• A throws clause can include more than one exception type.

• examplepublic int someMethod()throws

IOException, DivideByZeroException

Chapter 8 50

Accounting for Exceptions, cont.

• Some method in the calling hierarchy should handle the exception.

• If an exception is thrown, but never caught, either the program terminates or its behavior becomes unreliable.

Chapter 8 54

throws Clauses in Derived Classes

• When a method is redefined in a derived class, the redefined method cannot contain any exception classes that are not in the throws clause of the same method in the base class (though the derived class can list fewer exceptions in its throws clause).

• Any exceptions thrown in the derived class must be caught or thrown by the base class.

Chapter 8 56

Multiple Throws and Catches

• A try block can throw any number of different types of exceptions.

• Each catch block can catch only one type of exception.

• Multiple catch blocks after a try block can catch multiple types of exceptions.

Chapter 8 57

Multiple Throws and Catches, cont.

• class TwoCatchesDemo

Chapter 8 62

Java Tip: Catch the More Specific Exceptions First

• catch blocks are examined in order.• The first matching catch block is executed.• More specific exceptions should precede less

specific exceptions, i.e. exceptions lower in the exception hierarchy should come before exceptions higher in the exception hierarchy.

Chapter 8 64

Keep It Simple

• Attempt to modify a program or class definition so that it does not need a throw statement.

• In general, use exceptions sparingly.• If the way the exception is handled depends

on the calling method, let the calling method handle the exception.

• Consider throwing the exception and catching the exception in separate methods.

Chapter 8 65

Keep It Simple, cont.

public void methodB()

{

...

try

{

...

methodA();

...

}

catch (MyException e)

...

Chapter 8 86

Graphics Supplement: Exceptions in GUIs

• An uncaught exception in a (non-GUI) application will end the program.

• An uncaught exception in a GUI program (either a JFrame GUI or an applet) will not end the program.– However, unless the exception is caught,

the GUI may not cope correctly with the exception or the user may receive insufficient instructions.

Chapter 8 87

Programming Example: A JFrame Using Exceptions

• The example JFrame GUI allows the user to write the name of a color in a text field and to click the “Show Color” button.– If the GUI recognizes the color, the

background color changes to the named color.

– Otherwise, the text field displays “Unknown Color” and the background changes to gray.

Chapter 8 88

Programming Example: A JFrame Using Exceptions, cont.• class ColorDemo

Chapter 8 89

• class UnknownColorException

Programming Example: A JFrame Using Exceptions, cont.

Chapter 8 90

• class ShowColorDemo

Programming Example: A JFrame Using Exceptions, cont.

Chapter 8 91

Programming Example: A JFrame Using Exceptions, cont.

Chapter 8 92

throws Clause Not Allowed in actionPerformed

• A throws clause cannot be added to method actionPerformed in any action listener class.

• Any exception thrown in method actionPerformed must be caught in method actionPerformed.

• Similarly, if method windowClosing is redefined in a window listener class, you may not add a throws clause to method windowClosing.