LECTURE 8: EXCEPTIONS CSC 212 Data Structures. Error Handling Goals What should we do when an...

Preview:

DESCRIPTION

Exceptional Circumstances  ex-cep-tion : n.  Instance or case not conforming to the general rule  Proper way to signal error in object-oriented code  Seen Java exceptions in CSC111 already  Most are unchecked exceptions (no real solution)  ArrayIndexOutOfBoundsException -- accessing a nonexistent array entry  NullPointerException -- used reference that is equal to null

Citation preview

LECTURE 8:EXCEPTIONSCSC 212 – Data Structures

Error Handling Goals What should we do when an error

occurs? Should alert system to the error May want to execute code to handle to fix

error Minimize amount of rewritten code

May want to change in subclass Future inputs & uses of code should be

considered Changing printing of error message is not

possible

Exceptional Circumstances ex-cep-tion: n.

Instance or case not conforming to the general rule

Proper way to signal error in object-oriented code

Seen Java exceptions in CSC111 already Most are unchecked exceptions (no real solution) ArrayIndexOutOfBoundsException --

accessing a nonexistent array entry NullPointerException -- used reference that is

equal to null

Exception Classes Java Exception is a class defined by Java

Java defines many subclasses of Exception New Exception subclasses can be written, also

Error handling uses instances of these classes Classes are no different than others Will include fields, methods, & constructors

Exception instances are normal objects Use anywhere, not strictly for error handling Must instantiate before use

Throwing an Exceptionpublic class BankAccount { private float balance;

// Lots of code here… float withdraw(float amt) throws ReqException{ if (amt < 0) { throw new ReqException(); } else if (amt > balance) { ReqException re = new ReqException(); re.setBadRequest(amt, balance); throw re; } balance -= amt; return balance; }}

Error Handling Codes throw exception upon detecting problem Handle problem by catching exception Do not need to catch an exceptions

If it is never caught, program will crash Not a bad thing – had an unfixable error!

Handling Exceptions Once an exception is thrown, methods

can: Include code to catch exception and then

ignore it

Handling Exceptions Once an exception is thrown, methods

can: Include code to catch exception and then

ignore it Catch & handle exception so error is fixed

Handling Exceptions Once an exception is thrown, methods

can: Include code to catch exception and then

ignore it Catch & handle exception so error is fixed Catch the exception and throw a new one

Handling Exceptions Once an exception is thrown, methods

can: Include code to catch exception and then

ignore it Catch & handle exception so error is fixed Catch the exception and throw a new one Ignore exception so passed on to calling

method

Handling Exceptions Exception can be thrown anywhere &

anytime throws lists method’s fixable uncaught

exceptions void controller() throws LostPlane {…}int scheduler() throws NoFreeTime {…}

Calling methods now aware of possible errors If possible, could catch and correct errors List exception in own throws clause otherwisevoid plan(int i) throws NoFreeTime {

// Lots of interesting code here…scheduler();

}

try {…} Blocks Cannot catch exceptions thrown outside try blockvoid cantCatch() throws Oops, MyBadExcept {try { // There is code here that does something interesting… System.err.println(“This is not my exception”);} catch (Oops oop) { // Here be code…}methodThatMightThrowOopsExcept();throw new MyBadExcept();

}

try {…} Blocks Catch some (or all) exceptions thrown in try Each try needs at least 1 catch

void catchSome() throws MyBadException {try { methodThatMightThrowOops(); throw new MyBadExcept();} catch (Oops oop) { oop.printStackTrace(); System.err.println(“Oops was caught.”); System.err.println(“Method ends normally.”);}

}

try {…} Blocks try can have multiple catchs

void catchAll() {try { methodThatMightThrowOops(); methodThatShouldThrowOops(); throw new MyBadExcept();} catch (Oops oop) { oop.printStackTrace(); System.err.println(“Oops was caught.”); System.err.println(“Method ends normally.”);} catch (MyBadExcept mbe) { mbe.printStackTrace(); System.err.println(“MyBad was caught.”); System.err.println(“Method ends normally.”);}

}

Handling Exceptionspublic void forcedWithdrawal(float amount) throws BadRequestException {callPolice();addDyePacks();withdrawal(amount);

}

public void defeatOfJesseJames(float amt) {try { forcedWithdrawal(amt);} catch (BadRequestException bre) { formPosse(); killSomeGangMembers();} finally { giveLollipop();}

}

2 Types of Exceptions

Subclass of Exception Must list uncaught

exceptions in throws Use for fixable errors

Java forces methods to consider them

Only useful if fixable

Subclass of RuntimeException Can list uncaught

ones in throws “You are hosed”

Usually can’t be fixed Can ignore in method Still crashes program

unless it is caught

Checked Exception Unchecked Exception

Tracing Examplepublic static int generate() throws TraceException {

TraceException te = new TraceException();System.out.println(“Starting gE”);throw te;System.out.println(“Ending gE”);return 0;

}public static void handler(boolean callIt) {

try { System.out.println(“Starting cE”); if (callIt) { generate(); } System.out.println(“Ending cE”);} catch (TraceException te) { System.out.println(“Caught te”);}

}public static void main(String[] args) {

handler(false);handler(true);

}

Before Next Lecture… Continue week #3 weekly activity

Should now be able to do problems #1 & 2 Continue programming assignment #1

Assignment does not require any new material

Read about interfaces & abstract classes (Will form the basis of the mysterious ADT) Very important when working with GUIs Useful way of beating inheritence

Recommended