An Introduction to Java Programming and Object- Oriented Application Development Chapter 8...

33
An Introduction to Java Programming and Object-Oriented Application Development Chapter 8 Exceptions and Assertions

Transcript of An Introduction to Java Programming and Object- Oriented Application Development Chapter 8...

Page 1: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Introduction to Java Programming and Object-Oriented Application Development

Chapter 8Exceptions and Assertions

Page 2: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Objectives

In this chapter you will: Explore how Java throws and catches exceptions Become familiar with many of Java’s exception

classes Take a first look at the concept of inheritance Write code that handles exceptions thrown by a

Java program Create assertions to debug a program

Page 3: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Exceptions and Assertions

Applications should be robust, or well constructed Applications should be fault tolerant, or forgiving

of user mistakes Compile-time errors are violations of the

programming language syntax Runtime errors occur during program execution

and can cause a program to crash Logic errors produce incorrect output

Page 4: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Exception Handling

Runtime errors are referred to as exceptions When Java creates an exception object, it

throws the exception for further processing Two ways to handle exceptions

Do nothing: Let the Java runtime system handle it Write additional code to handle the exception

Handling the exception is preferable

Page 5: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Example of a Thrown Exception The error message produced by Java when an

exception is thrown is the stack trace The method-call stack is the sequence of method

calls that leads to creation of exception

Page 6: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Example of a Thrown Exception (continued)

Page 7: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Example of a Thrown Exception (continued) The exception was created in Line 48 of

NumberFormatException.java The method-call stack steps through each call to

a method, originating in Line 15 of main The stack trace gives a complete description of

the NumberFormatException object One option is to add logic to allow the user to

enter a greater variety of input

Page 8: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Example of a Thrown Exception (continued) When an exception is thrown, the Java runtime

system looks for code to handle the exception The method-call stack is checked for this code If no such code exists, the exception object is printed

and the program terminates If the exception were handled by the programmer,

the code could exit more gracefully The user could correct mistakes before the program

exited

Page 9: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Errors with Program Logic User input can be checked for validity using

additional logic As programs become more complex, handling

errors with additional logic becomes more complicated

Adding logic may make the program less readable Adding logic may make the program more difficult

to maintain

Page 10: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement Catching exceptions allows for customized

error statements The user can correct mistakes without

restarting the program The programmer needs three tools

The try blockThe catch blockThe finally block

Page 11: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement (continued) A try block begins with the keyword try

Contains statements where exceptions originate Contains statements that should normally execute

If an exception occurs, the rest of the try block is skipped

If an exception occurs, program control goes to the first catch block following the try block

Page 12: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement (continued) For each try block there is one or more catch

blocks There is one catch block for each type of

exception thrown A catch block begins with the keyword catch

and the exception parameter in parentheses When an exception is thrown, if a catch block

matches the exception type, it is executed

Page 13: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement (continued) After the catch block is executed, program

control continues after the last catch block An uncaught exception is handled by the Java

runtime system The object’s stack trace is displayed The program terminates

If no exceptions are thrown, the program skips all catch and finally blocks and processing continues normally

Page 14: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement (continued) The finally block is a set of statements

that always executesUseful for tasks like closing files

A try statement is the try, catch and finally blocks

e is the customary identifier for an exception object

Page 15: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement (continued) try statement syntax:try {

normal program statements } catch (TypeOfException_1 e) {

statements to process this exception } … catch (Type of Exception_n e) {

statements to process this exception } finally {

statements that always execute }

Page 16: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Handling Exceptions with the try Statement (continued) If a try statement is added to a program, a catch

statement must also be added Each catch statement handles one type of

exception A catch block executes only if an exception of the

specified type is thrown within the try block A finally block can be added immediately after

a try block or a combination of try and catch blocks

Page 17: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Classifying Exceptions

Exceptions can be classified according to an inheritance hierarchy

Exceptions can be classified as checked or unchecked

An inheritance hierarchy is like a taxonomy, a classification scheme according to common and unique characteristics

A subclass inherits from the class above it A superclass is above a subclass

Page 18: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Classifying Exceptions (continued)

Page 19: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Classifying Exceptions (continued) An unchecked exception inherits from the RuntimeException class

All other exception classes are checked Checked exceptions cause compiler errors if they are

not handled Unchecked exceptions do not cause compile-time

errors, but may cause runtime errors A throws clause follows the method declaration

throws TypeOfException1,TypeOfException2…

Page 20: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Multiple Catch Blocks and Programmer-Defined Exceptions The types of exceptions that can be thrown are

discovered through extensive testing catch blocks must immediately follow try

blocks with no intervening code A catch block for a more specific type of

exception should precede more general types Can use an IllegalArgumentException for

exception types not previously defined in Java An Exception object can also be used, but it is

poor programming practice

Page 21: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Propagating Exceptions

An exception propagator is a method that originates an exception

An exception catcher is the method that catches the exception

If an exception originates in a method but is not caught, the exception propagates up the method-call stack

The method-call stack is the sequence of method calls

Page 22: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Propagating Exceptions (continued)

Page 23: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Apply the Concept

The application divides two numbers, and is simple to showcase exception handling

A boolean flag thereIsAnError signals that an error or exception has occurred

Three methods are called in a while loop getDividend getDivisor calculateAndDisplay

The while loop executes while thereIsAnError is true

Page 24: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Apply the Concept (continued)

Exceptions are caught if the user terminates the application prematurely

Exceptions are caught if the user enters letters instead of digits

Exceptions originating in getDividend and getDivisor propagate to main

The method calculateAndDisplay catches an IllegalArgumentException if the divisor is zero

Page 25: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Apply the Concept (continued)

Page 26: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Apply the Concept (continued)

Page 27: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Assertions

Three major types of errorsCompile-time errorsRuntime errorsLogic errors

Compile-time errors are the result of syntax errors Runtime errors cause the program to terminate

while running Logic errors cause incorrect output

Page 28: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Using an Assertion

An assertion is designed to help the programmer detect logic errors

The syntax of an assert statement:assert expression : error message

The expression is a boolean expression that should always be true if the program is working

The error message is displayed if the expression ever becomes false

Assertions are placed after all values in expression have been determined

Page 29: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Example of an Assertion

An assert statement is placed to verify that kilograms are less than pounds

If the assertion is false, an AssertionError is thrown

The custom error is optional, but useful Compile with the –source 1.5 option Run with assertions enabled: -ea

Page 30: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

An Example of an Assertion (continued)

Page 31: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Summary

Programs can be made more robust and fault tolerant using exception handling

Exceptions are handled using a try statement The try statement consists of a try block, a catch block, and an optional finally block

Exceptions can be classified according to the inheritance hierarchy, or as checked or unchecked

The inheritance hierarchy is a taxonomy of Java classes

Page 32: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Summary (continued)

A subclass inherits from the class just above it The superclass is the class just above a given

class in the hierarchy Unchecked exceptions inherit from the RuntimeException class

All other exceptions are checked Checked exceptions must be handled or the

program will not compile

Page 33: An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Summary (continued)

Must be one catch block for every try block Each catch block handles one type of

exception Multiple catch blocks may follow a try block Exceptions that are not caught are propagated

up the method-call stack An assertion can be used to guarantee that

programmers don’t make major logic errors