Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 116/504 – Intro. To Computer Science for Majors II

Similar presentations


Presentation on theme: "CSE 116/504 – Intro. To Computer Science for Majors II"— Presentation transcript:

1 CSE 116/504 – Intro. To Computer Science for Majors II
Lecture 13: Exceptions Image used under Fair Use doctrine

2 Writing OO Methods Legos the goal for every class you will ever write
When used by others, interactions clearly defined Consistent across objects; states differ but hooks do not No other classes required; each instance self-contained Unlimited potential; does not assume specific uses

3 How do we create this perfection?
Writing OO Methods Legos the goal for every class you will ever write When used by others, interactions clearly defined Consistent across objects; states differ but hooks do not No other classes required; each instance self-contained Unlimited potential; does not assume specific uses How do we create this perfection?

4 Limit Data Lifespan Locals “live” for method or block within method
Name may be reused, but no relationship exists Parameters pass data between methods But receiving method must be called by sender Instance vars live between calls or even longer Values available with instance (or longer if static)

5 Locals always best choice Parameters & fields only as necessary
OO Key Concept #3 Locals always best choice Parameters & fields only as necessary

6 Locals always best choice
OO Key Concept #3 Locals always best choice Parameters & fields only as necessary (which is often)

7 Common Nightmare

8 Prevent the Nightmare Everyone tries keeping certain details private

9 Prevent the Nightmare Everyone tries keeping certain details private
Exposure limited to appropriate areas

10 Prevent the Nightmare Everyone tries keeping certain details private
Exposure limited to appropriate areas Limit how & why changes occur

11 Prevent the Nightmare Everyone tries keeping certain details private
Exposure limited to appropriate areas Limit how & why changes occur Stop others from seeing changes

12 Prevent the Nightmare Exact same holds for objects
Make fields private unless for very important reason: private int fieldName; Controls interactions since field accesses all in 1 file or

13 Declare fields private
OO Key Concept #4 Do NOT enable mistakes Declare fields private (unless absolutely needed)

14 Declare fields private
OO Key Concept #4 Do NOT enable mistakes Declare fields private (unless absolutely needed) (just rewrite the code if absolutely needed)

15

16 Error Handling Goals

17 Error Handling Goals What do we do when an error occurs?

18 Error Handling Goals What do we do when an error occurs?
Almost certainly copyright infringement, but this GIF is from via

19 Error Handling Goals What do should we do when an error occurs?
Alert application to error & stop execution Execute code handling error and crash if none exists Still lazy! Minimize code eventually rewritten How error handled & fixed WILL change with time Fixing stupid calls not story that we can always write How can we do this in object-oriented way?

20 Exceptional Circumstances
ex-cep-tion: n. Situation or case not conforming to the general rule Proper way to signal error in object-oriented code

21 Exceptional Circumstances
ex-cep-tion: n. Situation or case not conforming to the general rule Proper way to signal error in object-oriented code

22 Exception Classes Java
Exception is class defined by Java Java predefines many subclasses of Exception Unfortunately seen many Exception subclasses All are RuntimeExceptions -- unfixable errors IndexOutOfBoundsException NullPointerException StackOverflowException Java libraries define these Exceptions for us But like all of Java, just another class for us to use

23 2 Types of Exceptions Checked Exception Unchecked Exception

24 2 Types of Exceptions Checked Exception Unchecked Exception
Subclass of Exception throws must list uncaught Use for fixable errors Java forces methods to consider them Only useful if fixable Subclass of RuntimeException Can be listed in throws “You are hosed” Usually can’t be fixed Can ignore in method Unless it is caught, these will still crash program

25 2 Types of Exceptions Will crash program if uncaught
Checked Exception Unchecked Exception Subclass of Exception throws must list uncaught Use for fixable errors Java forces methods to consider them Only useful if fixable Will crash program if uncaught Subclass of RuntimeException Can be listed in throws “You are hosed” Usually can’t be fixed Can ignore in method Unless it is caught, these will still crash program Will crash program if uncaught

26 Usage identical for Checked & Unchecked Exceptions
2 Types of Exceptions Usage identical for Checked & Unchecked Exceptions

27 Writing Exception classes
Error handling based upon Exception classes Classes are not magic just subclass of Exception Classes can include fields, methods, & constructors Must create instances to have objects to use Also find Exception instances also not magic Can be used in error handling, but not required Like any other Java objects, can be used anywhere

28 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { 1

29 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { Convince your neighbor your answer is correct

30 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { 1

31 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { Package does NOT matter; Can create a new Exception class anywhere (plus I made up this package)

32 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { Name does NOT matter; Names usually ___Exception but can name class anything

33 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { Exception is a class; implements for interfaces

34 Which Is Exception Declaration?
package java.except; public class Slide { public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { Only requirement: must inherit from Exception (inheritance can be indirect)

35 Throwing an Exception public class BankAccount { private float balance; // Lots of code here… float withdraw(float amt) { if (amt < 0) { throw new RequestExcepton(); } else if (amt > balance) { RequestExcepton re = new RequestExcepton(); re.setBadRequest(amt, balance); throw re; } balance -= amt; return balance; } }

36 Correct Way to Raise Exception?
SlideException se; throw se; throw new SlideException(); throw SlideException(); throws new SlideException(); 1

37 Correct Way to Raise Exception?
SlideException se; throw se; throw new SlideException(); throw SlideException(); throws new SlideException(); Convince your neighbor your answer is correct

38 Correct Way to Raise Exception?
SlideException se; throw se; throw new SlideException(); throw SlideException(); throws new SlideException(); 1

39 Correct Way to Raise Exception?
SlideException se; throw se; public class SlideException{ public class Slide implements Exception { public class Slide extends Exception { Almost correct but must instantiate Exception to throw

40 Correct Way to Raise Exception?
SlideException se; throw se; throw new SlideException(); throw SlideException(); public class Slide extends Exception { Also close but Exception instance needed and none is created here!

41 Correct Way to Raise Exception?
SlideException se; throw se; throw new SlideException(); throw SlideException(); throws new SlideException(); Wrong keyword used: must use throws

42 Which Is Exception Declaration?
SlideException se; throw se; throw new SlideException(); throw SlideException(); throws new SlideException(); This is correct. Another way to write: SlideException se = new SlideException(); throw se;

43 After the throw

44 After the throw Image used under doctrines of Fair Use for educational purposes and/or freedom for parody.

45 try {…} catch {…} Blocks
Only exceptions in try block can be caught And not all exceptions: only ones with matching catch try { // Will handle any MistakeException raised in this area if (badThingHappening()) { throw new MistakeException(); } } catch (MistakeException oop) { // Handle and fix the problem } // More code could be here, but this is all made up throw new MistakeException();

46 try {…} catch {…} Blocks
Only exceptions in try block can be caught And not all exceptions: only ones with matching catch try { // Will handle any MistakeException raised in this area if (badThingHappening()) { throw new MistakeException(); } } catch (MistakeException oop) { // Handle and fix the problem } // More code could be here, but this is all made up throw new MistakeException(); If anything executed by try raises MistakeException

47 try {…} catch {…} Blocks
Only exceptions in try block can be caught And not all exceptions: only ones with matching catch try { // Will handle any MistakeException raised in this area if (badThingHappening()) { throw new MistakeException(); } } catch (MistakeException oop) { // Handle and fix the problem } // More code could be here, but this is all made up throw new MistakeException(); If anything executed by try raises MistakeException We can handle it in catch

48 try {…} catch {…} Blocks
Only exceptions in try block can be caught And not all exceptions: only ones with matching catch try { // Will handle any MistakeException raised in this area if (badThingHappening()) { throw new MistakeException(); } } catch (MistakeException oop) { // Handle and fix the problem } // More code could be here, but this is all made up throw new MistakeException(); If anything executed by try raises MistakeException We can handle it in catch But not when outside try

49 try {…} catch {…} Blocks
Can catch some (or all) exceptions from try Multiple fine, but every try needs at least 1 catch void catchSome() { try { methodThatMightThrowExceptions(); } catch (Oops oop) { // Handle and fix the problem for oop } catch (MistakeException me) { // Handle and fix the problem for me } }

50 throws Declaration Exception can be thrown anywhere & anytime
throws lists method’s uncaught exceptions void controller() throws LostPlane {…} int scheduler() throws NoFreeTime {…} throws provides warning to calling method Allows it to add try-catch block if it can handle error Exception not required, just warning it could happen

51 throws Declaration Warning of potential errors not just those thrown
Only care that Exception possible, not just started Does not matter if passed along from caller’s perspective If Exception can arise, should list in method’s throws int scheduler() throws NoFreeTime {…} void plan(int i) throws NoFreeTime { scheduler(); }

52 Not Handling Exceptions
float withdraw(float amt) throws BadReqEx { if (amt > balance) { BadReqEx re = new BadReqEx(amt,balance); throw re; } balance -= amt; return balance; } void forcedWithdrawal(float amount) { callPolice(); addDyePacks(); withdrawal(amount); public void robbedByJesseJames(float amt) { forcedWithdrawal(amt);

53 Not Handling Exceptions
float withdraw(float amt) throws BadReqEx { if (amt > balance) { BadReqEx re = new BadReqEx(amt,balance); throw re; } balance -= amt; return balance; } void forcedWithdrawal(float amount) { callPolice(); addDyePacks(); withdrawal(amount); public void robbedByJesseJames(float amt) { forcedWithdrawal(amt); Image used under Fair Use doctrine

54 Not Handling Exceptions
float withdraw(float amt) throws BadReqEx { if (amt > balance) { BadReqEx re = new BadReqEx(amt,balance); throw re; } balance -= amt; return balance; } void forcedWithdrawal(float amount) { callPolice(); addDyePacks(); withdrawal(amount); public void robbedByJesseJames(float amt) { forcedWithdrawal(amt); Unfair - by not stating exception, caller does not get chance to fix

55 Error Handling Story (1)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method also handled its errors, so not a problem throw statement included in try code block try had catch block for this Exception instance The code in that catch block handled the problem No other code needed – problem was solved ... And they lived happily ever after

56 Error Handling Story (1)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method also handled its errors, so not a problem throw statement included in try code block try had catch block for this Exception instance The code in that catch block handled the problem No other code needed – problem was solved ... And they lived happily ever after

57 Error Handling Story (1)
public int parseNum(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException nfe) { return 0; } }

58 Error Handling Story (2)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method did not handle error; passed up call chain throw either not in try or lacked matching catch Method called in try with catch for this Exception The code in that catch block handled the problem No other code needed – problem was solved ... And they lived happily ever after

59 Error Handling Story (2)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method did not handle error; passed up call chain throw either not in try or lacked matching catch Method called in try with catch for this Exception The code in that catch block handled the problem No other code needed – problem was solved ... And they lived happily ever after

60 Error Handling Story (2)
float secureWithdraw(float amt){ try { return withdraw(amt); } catch (BadReqEx var) { lockDoors(); callPolice(); return 0; } } float withdraw(float amt) throws BadReqEx { if (amt > balance) { throw new BadReqEx(amt,balance); } balance -= amt; return balance; }

61 Error Handling Story (3)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method did not handle error; passed up call chain throw either not in try or lacked matching catch Method call similar: not in try or not with catch Exception instance goes to method which called that Keeps going up calls until matching try-catch found

62 Error Handling Story (3)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method did not handle error; passed up call chain throw either not in try or lacked matching catch Method call similar: not in try or not with catch Exception instance goes to method which called that Keeps going up calls until matching try-catch found ... And they lived happily ever after

63 Error Handling Story (3)
float oceansEleven(){ try { planHeist(); hireCrew(); return robVaults( f); } catch (BadReqEx var) { return rewardFromServing(); } } float withdraw(float amt) throws BadReqEx { if (amt > balance) { throw new BadReqEx(amt,balance); } balance -= amt; return balance; }

64 Error Handling Story (4)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method did not handle error; passed up call chain throw either not in try or lacked matching catch Method call similar: not in try or not with catch Exception instance kept going through to main() No matching try-catch found in any method call ... And so the program crashed

65 Error Handling Story (4)
Once upon a time… an error was detected Method created instance from subclass of Exception Exception instance used in throw statement Method did not handle error; passed up call chain throw either not in try or lacked matching catch Method call similar: not in try or not with catch Exception instance kept going through to main() No matching try-catch found in any method call ... And so the program crashed

66 Handling Exceptions void forcedWithdrawal(float amount) throws BadReqEx{ callPolice(); addDyePacks(); withdrawal(amount); } public void northfieldMN(float amt) { try { forcedWithdrawal(amt); } catch (BadReqEx bre) { formPosse(); killSomeGangMembers(); } finally { giveLollipop(); }

67 Handling Exceptions void forcedWithdrawal(float amount) throws BadReqEx{ callPolice(); addDyePacks(); withdrawal(amount); } public void northfieldMN(float amt) { try { forcedWithdrawal(amt); } catch (BadReqEx bre) { formPosse(); killSomeGangMembers(); } finally { giveLollipop(); }

68 Locals always best choice
OO Key Concept #3 Locals always best choice Parameters & fields only as necessary (which is often)

69 Declare fields private
OO Key Concept #4 Do NOT enable mistakes Declare fields private (unless absolutely needed) (just rewrite the code if absolutely needed)

70 Usage identical for Checked & Unchecked Exceptions
2 Types of Exceptions Usage identical for Checked & Unchecked Exceptions

71 After the throw Image used under doctrines of Fair Use for educational purposes and/or freedom for parody.

72 For Next Lecture Reading is online (via website) for Friday
Even if not in book, reading remains required ADT and design pattern presented in one swoop How should Collections provide data access Week #5 weekly assignment due Monday Get started early; project phase #1 due Monday night


Download ppt "CSE 116/504 – Intro. To Computer Science for Majors II"

Similar presentations


Ads by Google