Docsity

Java Exception Handling: Preconditions, Checked Exceptions, and Custom Exceptions, Slides of Java Programming

Partial preview of the text

Download Java Exception Handling: Preconditions, Checked Exceptions, and Custom Exceptions and more Slides Java Programming in PDF only on Docsity!

Input using

BurrefedReader

Example

public

static

void

main(String[] args)

throws

IOException

BufferedReader

stdin

=^ new

BufferedReader(

new^

InputStreamReader(System.in));

System.out.print(“Enter

a^ String");

String

s^ =

stdin.readLine();

System.out.print(“You

Entered

s);

Accessor and Mutator Classes ^ Accessor•

Does not change the state of the implicitparameter (e.g.

getBalance

)

^ Mutator• changes the state of the implicit parameter

(e.g. deposit ) ^ Rule of thumb• Mutator should return void ^ Immutable class:• all methods are accessors (e.g.

String

)

Preconditions

^ Publish preconditions so the caller won'tcall methods with bad parameters/**

  • Deposits money into this account.* @param amount the amount of money todeposit* (Precondition:

amount >= 0

)

*/ ^ Typical use:• To restrict the parameters of a method• To require that a method is only called when

the object is in an appropriate state ^ Method can do

anything

if called when

precondition not fulfilled

Postcondition

^ Condition that's true after a method hascompleted.^ /**

*^ Deposits

money

into

this

account.

*^ (Postcondition:

getBalance()

>=^

0)

*^ @param

amount

the

amount

of^

money

to^

deposit

*^ (Precondition:

amount

=^

*/ ^ Don't document trivial postconditions that repeatthe

@return

clause

^ Contract• If caller fulfills precondition, method must fulfill

postcondition

BankAccount.java

/**A^ bank

account

has^ a balance

that^ can

be^ changed

by^ deposits

and^ withdrawals.*/

public class BankAccount

private

static

int^ lastAccountNumber; private

int^ accountNumber; private

double

balance; /**Constructs

a^ bank

account

with^ a^ zero^

balance*/

public BankAccount()

this(0);} /**Constructs

a^ bank

account

with^ a^ given

balance

*^ @param

initialBalance

the^ initial

balance*/

public BankAccount(double

initialBalance){

balance

=^ initialBalance; lastAccountNumber++;accountNumber

=^ lastAccountNumbre; } /**^ Deposits

money into^ the

bank^ account.

*^ @param

amount

the^ amount

to^ deposit*/

public void^ deposit(double

amount)

double^

newBalance

=^ balance

+^ amount;

balance

=^ newBalance; } /**Withdraws

money^

from^ the

bank^ account.

*^ @param

amount

the^ amount

to^ withdraw*/

public void^ withdraw(double

amount){

double^

newBalance

=^ balance

-^ amount;

balance

=^ newBalance; } /**Gets^ the^ current

balance

of^ the

bank^ account.

*^ @return

the^ current

balance

public double

getBalance()

{^ return

balance;

Reference Types: Consequences

public

class

Publication

{

private

String

author;

/*** Creates an instance of* Publication* @param

author the author of the publication

*/ public

Publication(String

author){

this.author

=^ author;

String

a; a^ =^

this.author; } }

this. author

a this. author

a

Java Packages

Importing Packages

^ Can always use class without importing^ java.awt.Color

backgroundColor = new

java.awt.Color(…)

^ Tedious to use fully qualified name ^ Import lets you use shorter class name^ import

java.awt.Color;

.^.^

. Color

backgroundColor

=^ new

Color(.

.^ .);

^ Can import all classes in a package^ import

java.awt.;* ^ Never need to import java.lang

Package Names

^ Package names should be unambiguous ^ Recommendation: start with reverseddomain name^ org.omg

.CORBA org.maju

.advprogramming

^ Path name should match package name^ org/maju/advprogramming/Course.java

Exception Handling

Goals

^ To learn how to throw exceptions ^ To be able to design your own exceptionclasses ^ To understand the difference betweenchecked and unchecked exceptions ^ To learn how to catch exceptions ^ To know when and where to catch anexception

Separating Error Handling Code  Traditional approach to error handling: methodreturns error code^ readFile {

open the file;determine its size;allocate that much memory;read the file into memory;close the file;}

^ What happens ifthe file can't be opened?the length of the file can't be determined?enough memory can't be allocated?if the read fails?if the file can't be closed? ^ To answer, you'd have to add a lot of code to doerror detection, reporting and handling

Separating Error Handling Code errorCodeType

readFile

initialize errorCode = 0; open the file; if (theFileIsOpen) {

determine the length of the file; if (gotTheFileLength) {

allocate that much memory; if (gotEnoughMemory) {

read the file into memory; if (readFailed) {

errorCode = -1;

} else { errorCode = -2; }

} else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) {

errorCode = -4;

} else {

errorCode = errorCode and -4;

} else {

errorCode = -5;

return errorCode;