DOC PREVIEW
UW-Madison CS 302 - Chapter 15 – Exception Handling

This preview shows page 1-2-3 out of 10 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Chapter 15 Chapter 15 ––Exception Exception HandlingHandlingWhat is a good program? A program What is a good program? A program that is reliable.that is reliable.Not just giving correct answer on Not just giving correct answer on correct inputcorrect inputShould protect against possible Should protect against possible errors (invalid password, not a errors (invalid password, not a picture file, etc)picture file, etc)15.1 Throwing Exceptions15.1 Throwing ExceptionsGood programsGood programsNeed a robust program, reliable to Need a robust program, reliable to the userthe userIt should not (It should not (““cannotcannot””) crash easily) crash easilyHow do we do this?How do we do this?Option 1 Option 1 ––return a special value to return a special value to determine if the method succeeded determine if the method succeeded or failedor failed––Ex. Make withdraw return true or falseEx. Make withdraw return true or falseWhatWhat’’s wrong with this?s wrong with this?––Calling method may not check answerCalling method may not check answer––Calling method may not know what to Calling method may not know what to dodoCatching ExceptionsCatching ExceptionsExceptionException––an error condition that can an error condition that can occur during the normal course of a occur during the normal course of a program executionprogram executionIn Java, exceptions are objects themselvesIn Java, exceptions are objects themselvesException handlingException handlingis another form of is another form of control structure (like ifs and switch control structure (like ifs and switch statements)statements)––When an error is encountered, the normal flow When an error is encountered, the normal flow of the program is stopped and the exception is of the program is stopped and the exception is handledhandledExceptionsExceptionsWe say an exception is We say an exception is thrownthrownwhen it when it occursoccursWhen the exceptionWhen the exception--handling code is handling code is executed, the error is executed, the error is caughtcaughtExamples:Examples:––Divide by zeroDivide by zero––Access a null objectAccess a null object––Array Index Out of BoundsArray Index Out of Bounds2Exception Program FlowException Program FlowWhat happens when exceptions occur?What happens when exceptions occur?––An Exception object is thrownAn Exception object is thrownWhat happens when an Exception is What happens when an Exception is thrown?thrown?––normal execution stops and exception handling normal execution stops and exception handling beginsbeginsWhat does the Exception object know?What does the Exception object know?––the name of the problemthe name of the problem––the location where it occurredthe location where it occurred––and moreand more……Why have exception handling?Why have exception handling?consistency (everyone else does it)consistency (everyone else does it)––Java API classes use exceptions.Java API classes use exceptions.––Other programming languages do too!Other programming languages do too!flexibilityflexibility––Programmer can decide how to fix problems.Programmer can decide how to fix problems.simplicitysimplicity––Easy to pinpoint problems.Easy to pinpoint problems.FoodIteratorFoodIteratorfifi= = afc.getAllFoodafc.getAllFood();();while ( !while ( !hasFoodhasFood() && () && fi.hasNextfi.hasNext() ) {() ) {Food f = Food f = fi.getNextFoodfi.getNextFood();();if ( if ( f.getLocation().equals(myLocf.getLocation().equals(myLoc) )) )myFoodmyFood=f;=f;}}}}What exceptions can occur?What exceptions can occur?NullPointerExceptionpublic double divide( int data1, int data2 ){return data1 / data2;}What exceptions can occur?What exceptions can occur?Arithmetic Exception: divide by zeroHow to handle Exceptions?How to handle Exceptions?Do nothingDo nothingprogram crashes if the exception occurs!program crashes if the exception occurs!Propagate (throws) itPropagate (throws) ittell the methodtell the method’’s caller about it and let s caller about it and let them decide what to dothem decide what to doResolve (tryResolve (try--catch) it in our methodcatch) it in our methodfix it or tell the user about it and let them fix it or tell the user about it and let them decide what to dodecide what to doExceptionsExceptionsSo far, we have let the system handle So far, we have let the system handle exceptionsexceptionsintintscore = score = in.nextIntin.nextInt();();If the user enters If the user enters ““abc123abc123””Exception in thread "main" Exception in thread "main" java.util.InputMismatchExceptionjava.util.InputMismatchExceptionat java.util.Scanner.throwFor(Scanner.java:819)at java.util.Scanner.throwFor(Scanner.java:819)at java.util.Scanner.next(Scanner.java:1431)at java.util.Scanner.next(Scanner.java:1431)at java.util.Scanner.nextInt(Scanner.java:2040)at java.util.Scanner.nextInt(Scanner.java:2040)at java.util.Scanner.nextInt(Scanner.java:2000)at java.util.Scanner.nextInt(Scanner.java:2000)at Test.main(Test.java:5)at Test.main(Test.java:5)3Says in English:Says in English:––System has caught an error described as a System has caught an error described as a InputMismatchExceptionInputMismatchException––Thrown because a String cannot be Thrown because a String cannot be converted to an integerconverted to an integerWhen system handles, we often get a When system handles, we often get a program crashprogram crashInstead of the system, we can handle to Instead of the system, we can handle to improve robustnessimprove robustnessThrowing ExceptionsThrowing ExceptionsIf there is an error in the value of a If there is an error in the value of a parameter, we can throw parameter, we can throw exceptions to make the user exceptions to make the user accountableaccountable1.1.Decide what type of exception to Decide what type of exception to throwthrow2.2.Test for condition, and throw the Test for condition, and throw the exception if condition is violatedexception if condition is violatedExampleExampleThrow an exception object to signal Throw an exception object to signal an exceptional condition an exceptional condition Example: What do we do if the Example: What do we do if the amount to withdraw is greater than amount to withdraw is


View Full Document

UW-Madison CS 302 - Chapter 15 – Exception Handling

Download Chapter 15 – Exception Handling
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Chapter 15 – Exception Handling and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Chapter 15 – Exception Handling 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?