75
Exception Handling and Format output

Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Embed Size (px)

Citation preview

Page 1: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Exception Handlingand Format output

Page 2: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Midterm exam

• Date: Nov 1st, 2006• Content:

Week 1 to Week 8Format:

Multiple choiceDetermine the results of the codeWrite simple code

Page 3: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Project 1 - Documentation

• Description of a class (an important method should be described in a similar way)

public class Report extends java.lang.ObjectPURPOSE: This program produces a report for the eBooks Company showing

the sales totals for each genre, and in each genre, broken down for each month when this particular genre is for sale. Using information about each sale transaction including genre, month (of the transaction), ISBN of the book prints a summary line for each month (belongs to each specific genre) and each genre At the end of the report, the total number of books sold, the total money, the most active genre will be printed. DATA: The program reads a text file named SAMPLEBOOK.txt. Each line of the file should represent one transaction from eBooks in the following format: ISBN Column 1–Column 9 Title Column 10- Column 49 Genre Column 50 -Column 62 Price Column 63-Column 68 PublishedYear Column 69-Column 72 Day Column 73 – Column 74 Month Column 75 – Column 76 Lines of the file must be sorted by genre, and in each genre, sorted by month

Page 4: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Project 1 - Documentation

• Internal comments:Remember to comments on the code,

especially when you have do

• Define constantsdon’t just use 10, 12

Page 5: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Introduction

• Exception – an indication of a problem that occurs during a program’s execution

• Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully

• Exception handling enables programmers to create programs that are more robust and fault-tolerant

Page 6: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Introduction

• Examples– ArrayIndexOutOfBoundsException – an

attempt is made to access an element past the end of an array

– NullPointerException – when a null reference is used where an object is expected

Page 7: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Exception-Handling Overview

• Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug

• Exception handling enables programmers to remove error-handling code from the “main line” of the program’s execution

• Improves clarity• Enhances modifiability

Page 8: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Example: Not Catching Exceptions

String inputStr;

int age;

inputStr = JOptionPane.showInputDialog(null, "Age:");

age = Integer.parseInt(inputStr);

Error message for invalid input

Exception in thread "main" java.lang.NumberFormatException: For input string: "ten"at java.lang.NumberFormatException.forInputString(Unknown Source)at java.lang.Integer.parseInt(Unknown Source)at java.lang.Integer.parseInt(Unknown Source)at Week7.SimpleException.main(SimpleException.java:12)

Page 9: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Catching an ExceptioninputStr = JOptionPane.showInputDialog(null, "Age:");

try {

age = Integer.parseInt(inputStr);

} catch (NumberFormatException e){

JOptionPane.showMessageDialog(null, "’" + inputStr

+ "‘ is invalid\n"

+ "Please enter digits only");

}

try

catch

Page 10: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Performance Tip

If the potential problems occur infrequently, intermixing program and error-handling logic can degrade a program’s performance, because the program must perform (potentially frequent) tests to determine whether the task executed correctly and the next task can be performed.

Page 11: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Try-catch: what does that mean?

When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught.

Page 12: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Try-catch: what does that mean?

• try block – encloses code that might throw an exception and the code that should not execute if an exception occurs

• Consists of keyword try followed by a block of code enclosed in curly braces

Page 13: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Try-catch: what does that mean?

• catch block – catches (i.e., receives) and handles an exception, contains:– Begins with keyword catch– Exception parameter in parentheses –

exception parameter identifies the exception type and enables catch block to interact with caught exception object

– Block of code in curly braces that executes when exception of proper type occurs

Page 14: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Try-catch: what does that mean?

• Matching catch block – the type of the exception parameter matches the thrown exception type exactly or is a superclass of it

• Uncaught exception – an exception that occurs for which there are no matching catch blocks– Cause program to terminate if program

has only one thread; Otherwise only current thread is terminated and there may be adverse effects to the rest of the program

Page 15: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

try-catch Control Flow

Page 16: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Project 3 discussion

Read a line from the data file

That line is not null?

Use StringTokenizer with delimiter =“;”Create an object with the newly extracted field

Checking for error using that object*

Read a line from the data file

Page 17: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Project 3 discussion

• Checking for invoice code:If (<string object>.length() < 6)

error AElse if (invoice code doesn’t start with 3 capital

letters) error B

Else if (invoice code has 3 000 at the end)error C

Else error V

Page 18: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

try-catch Control Flow

• When an exception occurs:– try block terminates immediately– Program control transfers to first matching catch

block

• After exception is handled:– Termination model of exception handling – program

control does not return to the throw point because the try block has expired; Flow of control proceeds to the first statement after the last catch block

– Resumption model of exception handling – program control resumes just after throw point

Page 19: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

try-catch Control Flow

• try statement – consists of try block and corresponding catch and/or finally blocks

Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.

Page 20: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Tip

With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. This helps ensure the kind of robust applications that contribute to what is called mission-critical computing or business-critical computing.

Page 21: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

To catch an exception, code must be enclosed in a

a. throws block.b. catch block.c. try block.d. finally block.

Page 22: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

To catch an exception, code must be enclosed in a

a. throws block.b. catch block.c. try block.d. finally block.

Page 23: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

An uncaught exception:a. is a possible exception that never actually

occurs during the execution of the program.b. is an exception that occurs for which the

matching catch clause is empty.c. is an exception that occurs for which there

are no matching catch clauses.d. is another term for a thrown exception

Page 24: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

An uncaught exception:a. is a possible exception that never actually

occurs during the execution of the program.b. is an exception that occurs for which the

matching catch clause is empty.c. is an exception that occurs for which there

are no matching catch clauses.d. is another term for a thrown exception

Page 25: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Getting Information

• There are two methods we can call to get information about the thrown exception:– getMessage– printStackTracetry {

. . .

} catch (NumberFormatException e){

System.out.println(e.getMessage());

System.out.println(e.printStackTrace());

}

Page 26: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

printStackTrace, getStackTrace and getMessage

• Methods in class Throwable retrieve more information about an exception– printStackTrace – outputs stack trace to

standard error stream– getStackTrace – retrieves stack trace

information as an array of StackTraceElement objects; enables custom processing of the exception information

– getMessage – returns the descriptive string stored in an exception

Page 27: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Multiple catch Blocks• A single try-catch statement can include multiple

catch blocks, one for each type of exception.

try {

. . .

age = Integer.parseInt(inputStr);

// Asuming I have a file I/O here

. . .

} catch (NumberFormatException e){

. . .

} catch (FileNotFoundException file_error){

. . .

}

Page 28: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Multiple catch Control Flow

Page 29: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

The finally Block

• There are situations where we need to take certain actions regardless of whether an exception is thrown or not.

• We place statements that must be executed regardless of exceptions in the finally block.

Page 30: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

try-catch-finally Control Flow

Page 31: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Propagating Exceptions

• Instead of catching a thrown exception by using the try-catch statement, we can propagate the thrown exception back to the caller of our method.

• The method header includes the reserved word throws.

public int getAge( ) throws NumberFormatException {

. . .

int age = Integer.parseInt(inputStr);

. . .

return age;

}

Page 32: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Throwing Exceptions

• We can write a method that throws an exception directly, i.e., this method is the origin of the exception.

• Use the throw reserved to create a new instance of the Exception or its subclasses.

• The method header includes the reserved word throws.

public void doWork(int num) throws Exception {

. . .

if (num != val) throw new Exception("Invalid val");

. . .

}

Page 33: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Sample Call Sequence

Page 34: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Exception Thrower

• When a method may throw an exception, either directly or indirectly, we call the method an exception thrower.

• Every exception thrower must be one of two types:– catcher.– propagator.

Page 35: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

Which of the following is not true regarding the throw point of an exception?

a. It specifies the point at which the exception must be handled.

b. It is the initial point at which the exception occurs.

c. It is specified as the top row of the method-call stack at the time the exception occurred.

d. All of the above statements are true.

Page 36: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

Which of the following is not true regarding the throw point of an exception?

a. It specifies the point at which the exception must be handled.

b. It is the initial point at which the exception occurs.

c. It is specified as the top row of the method-call stack at the time the exception occurred.

d. All of the above statements are true.

Page 37: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

Which of the following is not true regarding the throw point of an exception?

a. It specifies the point at which the exception must be handled.

b. It is the initial point at which the exception occurs.

c. It is specified as the top row of the method-call stack at the time the exception occurred.

d. All of the above statements are true.

Page 38: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review question

Which of the following statements is not true?a. Exception handling enables programmers to write robust and fault-tolerant programs.b. Exception handling can only catch the exception but cannot resolve the exception.c. Exception handling can resolve exceptions.d. The Java 2 Platform, Standard Edition, Version 1.4 introduced the new chained exception feature.

Page 39: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review question

Which of the following statements is not true?a. Exception handling enables programmers to write robust and fault-tolerant programs.b. Exception handling can only catch the exception but cannot resolve the exception.c. Exception handling can resolve exceptions.d. The Java 2 Platform, Standard Edition, Version 1.4 introduced the new chained exception feature.

Page 40: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Debugging 101

• execute your Java program line by line • examine the value of variables at

different points in the program How to do:

set a breakpoint in your code so the debugger suspends execution (double-click in

the gray margin on the left side of the editor )choose Run -> Debug As -> Java Applications

Page 41: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Types of Exception Throwers

• An exception catcher is an exception thrower that includes a matching catch block for the thrown exception.

• An exception propagator does not contain a matching catch block.

• A method may be a catcher of one exception and a propagator of another.

Page 42: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Using the throws Clause

• throws clause – specifies the exceptions a method may throws– Appears after method’s parameter list and

before the method’s body– Contains a comma-separated list of exceptions– Exceptions can be thrown by statements in

method’s body of by methods called in method’s body

– Exceptions can be of types listed in throws clause or subclasses

Page 43: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

When to Use Exception Handling

• Exception handling designed to process synchronous errors

• Synchronous errors – occur when a statement executes

• Asynchronous errors – occur in parallel with and independent of the program’s flow of control

Page 44: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Java Exception Hierarchy

• All exceptions inherit either directly or indirectly from class Exception

• Exception classes form an inheritance hierarchy that can be extended

• Class Throwable, superclass of Exception– Only Throwable objects can be used with the

exception-handling mechanism– Has two subclasses: Exception and Error

• Class Exception and its subclasses represent exception situations that can occur in a Java program and that can be caught by the application

• Class Error and its subclasses represent abnormal situations that could happen in the JVM – it is usually not possible for a program to recover from Errors

Page 45: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Portion of class Throwable’s inheritance hierarchy.

Page 46: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Checked vs. Runtime

• There are two types of exceptions:– Checked/Compiling time– Unchecked/Run time

• A checked exception is an exception that is checked at compile time.

• All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime.

Page 47: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Different Handling Rules

• When calling a method that can throw checked exceptions – use the try-catch statement and place the

call in the try block, or – modify the method header to include the

appropriate throws clause.

• When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.

Page 48: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Handling Checked/Compiling Exceptions

Page 49: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Handling Unchecked/Runtime Exceptions

Page 50: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Java Exception Hierarchy

• Two categories of exceptions: checked and unchecked

• Checked exceptions– Exceptions that inherit from class Exception

but not from RuntimeException– Compiler enforces a catch-or-declare

requirement– Compiler checks each method call and

method declaration to determine whether the method throws checked exceptions. If so, the compiler ensures that the checked exception is caught or is declared in a throws clause. If not caught or declared, compiler error occurs.

Page 51: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Java Exception Hierarchy

• Unchecked exceptions– Inherit from class RuntimeException

or class Error– Compiler does not check code to see if

exception is caught or declared– If an unchecked exception occurs and

is not caught, the program terminates or runs with unexpected results

– Can typically be prevented by proper coding

Page 52: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Java Exception Hierarchy

• catch block catches all exceptions of its type and subclasses of its type

• If there are multiple catch blocks that match a particular exception type, only the first matching catch block executes

• It makes sense to use a catch block of a superclass when all the catch blocks for that class’s subclasses will perform the same functionality

Page 53: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Outline

try { statements } // end try catch ( AKindOfException exception1 ) { exception-handling statements } . . . catch ( AnotherKindOfException exception2 ) { exception-handling statements } finally { statements }

Page 54: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

Exceptions can occur:a. from the Java Virtual Machine.b. through explicitly mentioned code in a

try block.c. through calls to other methods made in

a try block.d. All of the above.

Page 55: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

Exceptions can occur:a. from the Java Virtual Machine.b. through explicitly mentioned code in a

try block.c. through calls to other methods made in

a try block.d. All of the above.

Page 56: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

In the catch block below, what is nullPointerException? catch (NullPointerException nullPointerException ) { System.err.println(“nullPointerException”); } // end catch a. The type of the exception being caught.b. The name of catch block’s exception parameter.c. A finally block.d. An exception handler.

Page 57: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Review

In the catch block below, what is nullPointerException? catch (NullPointerException nullPointerException ) { System.err.println(“nullPointerException”); } // end catch a. The type of the exception being caught.b. The name of catch block’s exception parameter.c. A finally block.d. An exception handler.

Page 58: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Throwing Exceptions Using the throw Statement

• throw statement – used to throw exceptions

• Programmers can thrown exceptions themselves from a method if something has gone wrong

• throw statement consists of keyword throw followed by the exception object

Page 59: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Rethrowing Exceptions

• Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it

• Exception is deferred to outer try statement

• Exception is rethrown by using keyword throw followed by a reference to the exception object

Page 60: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Stack Unwinding

• Stack unwinding – When an exception is thrown but not caught in a particular scope, the method-call stack is “unwound,” and an attempt is made to catch the exception in the next outer try block.

Page 61: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Stack Unwinding

• When unwinding occurs:– The method in which the exception was not

caught terminates– All local variables in that method go out of

scope– Control returns to the statement that

originally invoked the method – if a try block encloses the method call, an attempt is made to catch the exception.

Page 62: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Declaring New Exception Types

• You can declare your own exception classes that are specific to the problems that can occur when another program uses your reusable classes

• New exception class must extend an existing exception class

Page 63: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Declaring New Exception Types

• Typically contains only two constructors– One takes no arguments, passes a default

exception messages to the superclass constructor

– One that receives a customized exception message as a string and passes it to the superclass constructor

Page 64: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Preconditions and Postconditions

• Preconditions and postconditions are the states before and after a method’s execution

• Used to facilitate debugging and improve design

• You should state the preconditions and postconditions in a comment before the method declaration

Page 65: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Preconditions and Postconditions

• Preconditions– Condition that must be true when the

method is invoked– Describe method parameters and any other

expectations the method has about the current state of a program

– If preconditions not met, method’s behavior is undefined

Page 66: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Preconditions and Postconditions

• Postconditions– Condition that is true after the method

successfully returns– Describe the return value and any other

side-effects the method may have– When calling a method, you may assume

that a method fulfills all of its postconditions

Page 67: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Assertions

• Assertions are conditions that should be true at a particular point in a method

• Help ensure a program’s validity by catching potential bugs

• Preconditions and Postconditions are two kinds of assertions

• Assertions can be stated as comments or assertions can be validated programmatically using the assert statement

Page 68: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Assertions

• The syntax for the assert statement isassert <boolean expression>;

where <boolean expression> represents the condition that must be true if the code is working correctly.

• If the expression results in false, an AssertionError (a subclass of Error) is thrown.

Page 69: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Sample Use #1public double deposit(double amount) {

double oldBalance = balance;balance += amount;

assert balance > oldBalance;}

public double withdraw(double amount) {double oldBalance = balance;balance -= amount;

assert balance < oldBalance;}

Page 70: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Second Form

• The assert statement may also take the form:

assert <boolean expression>: <expression>;

where <expression> represents the value passed as an argument to the constructor of the AssertionError class. The value serves as the detailed message of a thrown exception.

Page 71: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Sample Use #2

public double deposit(double amount) {

double oldBalance = balance;

balance += amount;

assert balance > oldBalance :"Serious Error – balance did not " +" increase after deposit";

}

Page 72: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Compiling Programs with Assertions

• Before Java 2 SDK 1.4, the word assert is a valid nonreserved identifier. In version 1.4 and after, the word assert is treated as a regular identifier to ensure compatibility.

• To enable the assertion mechanism, compile the source file using

javac –source 1.4 <source file>

Page 73: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Format Outputs

Page 74: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Introduction

• Class Formatter– Formats and outputs data to a specified

destination• E.g., a string or a file output stream

Page 75: Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the

Streams

• Streams– Sequences of bytes– Can often be redirected

• Standard input – keyboard• Standard output – screen• Standard error – screen• More in Chapters 14 and 24