18
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures

LECTURE 8: EXCEPTIONS CSC 212 Data Structures. Error Handling Goals What should we do when an error occurs? Should alert system to the error May

Embed Size (px)

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

Page 1: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

LECTURE 8:EXCEPTIONSCSC 212 – Data Structures

Page 2: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 3: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 4: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 5: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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; }}

Page 6: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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!

Page 7: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

Handling Exceptions Once an exception is thrown, methods

can: Include code to catch exception and then

ignore it

Page 8: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 9: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 10: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 11: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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();

}

Page 12: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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();

}

Page 13: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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.”);}

}

Page 14: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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.”);}

}

Page 15: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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();}

}

Page 16: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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

Page 17: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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);

}

Page 18: LECTURE 8: EXCEPTIONS CSC 212  Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May

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