question of the day a landscaper plants 5 rows of 4 trees each, but only uses 10 trees. how is this...
TRANSCRIPT
Question of the Day
A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
Question of the Day
A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
Question of the Day
A landscaper plants 5 rows of 4 trees each, but only uses 10 trees. How is this possible?
LECTURE 14:EXCEPTIONS
Error Handling Goals
Error Handling Goals
What should we do when an error occurs? Should alert system to the error Stop immediately and execute code
handling error Minimize amount of rewritten code
How error handled & fixed may change in subclass
Unknown future uses of code demands flexibility
Changing printing of error message is not possible
Exceptional Circumstances
ex-cep-tion: n. Situation or case not conforming to the
general rule Proper way to signal error in object-
oriented code
Seen Java exceptions in CSC111 already Most of these were unchecked (not
solvable) ArrayIndexOutOfBoundsException --
accessing a nonexistent array entry NullPointerException -- used null
reference
Exception Classes Java
Exception is class defined by Java Java already defines many subclasses of Exception
New Exception subclasses can be written, also
Error handling uses instances of these classes Classes are not magic and work like all
others Classes can include fields, methods, &
constructors Exception instances not special, either
Must instantiate before use Use anywhere, not strictly for error
handling
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 if the error was unfixable,
however
Throwing an Exception
public 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; }}
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 it would like, 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
Can only catch exceptions thrown in try block
void cantCatch() throws MistakeExcept,MyBadExcept{try { // There is code here that does something interesting… System.err.println(“No exceptions”);} catch (Oops oop) { // Here be code to fix the exception}methodThatMightThrowMistakeExcept();throw new MyBadExcept();
}
try {…} Blocks
Can only catch exceptions thrown in try block
void cantCatch() throws MistakeExcept,MyBadExcept{try { // There is code here that does something interesting… System.err.println(“No exceptions”);} catch (Oops oop) { // Here be code to fix the exception}methodThatMightThrowMistakeExcept();throw new MyBadExcept();
}
try {…} Blocks
Can catch some (or all) exceptions from try Each try needs at least 1 catch
void catchSome() throws MyBadException {try { methodThatMightThrowExceptions(); throw new MyBadExcept();} catch (Oops oop) { oop.printStackTrace(); System.err.println(“Method ends normally.”);} catch (MistakeException me) { System.err.println(“Boy was I dumb!”);}
}
try {…} Blocks
If exception thrown, stop try & go to catchvoid catchAll() {try { methodThatMightThrowOops(); methodThatShouldThrowOops(); throw new MyBadExcept();} catch (Oops oop) { oop.printStackTrace(); System.err.println(“Oops was handled.”);} catch (MyBadExcept mbe) { mbe.printStackTrace(); System.err.println(“MyBad fixed.”);}
}
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);
}
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 hasn't chance to handle
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();}
}
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();}
}
2 Types of Exceptions
Checked Exception Unchecked Exception
2 Types of Exceptions
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
Checked Exception Unchecked Exception
Tracing Example
public static void generate() throws TraceException {TraceException te = new TraceException();throw te;System.out.println(“Ending gE”);
}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);
}
Tracing Example
public static void generate() throws TraceException {TraceException te = new TraceException();throw te;System.out.println(“Ending gE”);
}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);
}
Tracing Example
public static void generate() throws TraceException {TraceException te = new TraceException();throw te;
}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);
}
Your Turn
Get into your groups and complete activity
For Midterm
You can use on this midterm: You can always use your textbook & notes Printout of slides IF has notes on that day's
slides At the same time, you may NOT use:
Computer, calculator, cell phone, or similar Copies of daily activities and/or solutions Friends, Romans, countrymen or their ears
To be certain rules are followed, when test ends Hand in all printed material you had with
you
How to Prepare for Midterm
DO DON'T
Make cheat sheets for the test
Review how parts of Java work
Add post-its to important pages
Memorize Drink case of 40s before
test Use post-its as clothing