1 / 40

Exceptions

Exceptions. Chapter 9. Outcomes. Find the exception that crashed a program find where it happened in your code Understand how try-catch blocks work Write a try-catch block to catch exceptions your program might throw Design and place try-catch blocks so your program recovers gracefully.

bozica
Download Presentation

Exceptions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exceptions Chapter 9

  2. Outcomes • Find the exception that crashed a program • find where it happened in your code • Understand how try-catch blocks work • Write a try-catch block to catch exceptions your program might throw • Design and place try-catch blocks so your program recovers gracefully

  3. Exceptional Circumstances • Reading numbers from user • User types in a word • not the sort of thing we expected • program crashes Enter a number: 20 Enter another number: done Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) see SumNumbers.java

  4. Exceptional Circumstances • Reading file name from user • User gives name of a file that doesn’t exist • can’t open that file for input • program crashes Enter the name of a file and I will sum its numbers: noSuchFile.txt Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20) see SumUsersFile.java

  5. Exceptions • Our Scanner has thrown an exception • Exception in thread “main” java.util.InputMismatchException • Exception in thread “main” java.io.FileNotFoundException • It ran into an error it couldn’t fix • program “crashed” • eventually!

  6. What Exception? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20)

  7. Where? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) Exception in thread "main" java.io.FileNotFoundException: noSuchFile.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at java.util.Scanner.<init>(Scanner.java:636) at SumUsersFile.main(SumUsersFile.java:20)

  8. Where??? • Methods call other methods • which may call other methods in turn • One method throws the exception • error message shows whole “stack” of calls main nextDouble Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26) next throwFor

  9. Look for Your Program • Many of the methods don’t belong to you • you can’t do anything about them • Some of the programs are yours • that’s where you can do something • line 26 of SumNumbers.java Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:26)

  10. Exercise • Where did this exception get thrown from? • What methods were called? • What line(s) of your program are relevant? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at csci1227.Scanner.nextInt(Scanner.java:169) at ArraySearcher.search(ArraySearcher.java:178) at ArraySearcher.main(ArraySearcher.java:58)

  11. Catching Exceptions • try-catch block try { … // code that may throw an exception } catch(ExceptionClassexceptionObject) { … // code to handle the exception } • Try to do this, and if something goes wrong, do this to deal with it

  12. Caught or Declared? • Exceptions must be caught or declared • try-catch  exception is caught • throws  exception is declared • Don’t catch them  need to declare them • Catch them  don’t declare them • take the “throws” clause(s) away Only some exceptions need to be caught or declared. FileNotFoundException needs to be caught or declared. Others we look at today don’t need to be caught or declared, but we’ll catch them anyway – to make our programs nicer.

  13. Catching Exceptions • For catching InputMismatchException • inside the number-reading loop try { num = kbd.nextDouble(); // may throw an exception kbd.nextLine(); } catch(InputMismatchExceptionime) { System.out.println(“That’s not a number!”); break; // exit from loop } Note: it’s a parameter! see CatchInputMismatch.java

  14. When No Exceptions Occur while (num >= 0.0) { sum += num; System.out.print(“Enter another number: ”); try { num = kbd.nextDouble(); kbd.nextLine(); } catch(InputMismatchException e) { System.out.println(“That’s not a number!”); break; // exit from loop } }

  15. When An Exception Occurs while (num >= 0.0) { sum += num; System.out.print(“Enter another number: ”); try { num = kbd.nextDouble(); // doesn’t even get to finish! kbd.nextLine(); } catch(InputMismatchException e) { System.out.println(“That’s not a number!”); break; // exit from loop } }

  16. Notes • InputMismatchException part of java.util • needs to be imported along with Scanner import java.util.Scanner; import java.util.InputMismatchException; • Our program exits the loop because of the break command • normally would continue on inside the loop • (or whatever comes after the catch block)

  17. Dealing with Exceptions • After catching the exception, the body of the catch block is executed • does whatever it says to do • print a message; break out of a loop • Question to ask yourself: • What do I want my program to do when it catches this exception?

  18. Exercise • What happens with the following code when the user enters a non-number? while (num >= 0.0) { sum += num; System.out.print(“Enter another number: ”); try { num = kbd.nextDouble(); kbd.nextLine(); } catch(InputMismatchException e) { System.out.println(“That’s not a number!”); kbd.nextLine(); } } • What goes wrong? • How might we fix it?

  19. Bigger Try Blocks • Enter a word instead of the first number • program crashes! • Catch blocks only catch exceptions from the corresponding try blocks • exceptions from outside don’t get caught • Try block can be as big as you want • so long as it stays inside the method

  20. A Loop inside a try Block • Exception  stop reading numbers • even if it’s the first number! int sum = 0; try { int num = kbd.nextInt(); while (num >= 0) { sum += num; num = kbd.nextInt(); } } catch (InputMismatchExceptionime) {} System.out.println(“The sum is ” + sum);

  21. Exercise • Revise the code so that the sum is only printed if the loop ends “normally” • that is, by the user entering a negative number int sum = 0; try { int num = kbd.nextInt(); while (num >= 0) { sum += num; num = kbd.nextInt(); } } catch (InputMismatchExceptionime) {} System.out.println(“The sum is ” + sum);

  22. File Not Found Exceptions • In file i/o we have FileNotFoundExceptions • generated when try to create a Scanner • or a PrintWriter • What do we want to happen? • end the program (gracefully!) • give user another chance • maybe after 3 chances end the program • use a default file or value

  23. End the Program • Catch block should also print error message try { System.out.print(“Enter file name: ”); Scanner fin = new Scanner(new File(fileName)); // read from the file using fin here fin.close(); } catch (FileNotFoundExceptionfnf) { System.err.println(“File not found. Quitting.”); System.exit(1); }

  24. System.exit • End the program • takes one argument: program return code • System.exit(0)  everything finished fine • System.exit(1)  something went wrong • System.exit(2)  something (else) went wrong • System.exit(3)  something (else else) ... • Usually only need (0) and (1) • otherwise NAME your return codes (finalvars)

  25. Exercise • Revise this code to exit program if the file SecretPlanet.txt can’t be found public Planet ReadPlanetFromFile() throws FileNotFoundException { Scanner fin = new Scanner(new File(“SecretPlanet.txt”)); String aName = fin.nextLine(); intaCode = fin.nextInt(); double aDist = fin.nextDouble(); fin.close(); return new Planet(aName, aDist, aCode); }

  26. Give User Another Chance • Print warning message and try again • need a loop with try-catch block inside it Scanner fin = null; while (fin == null) { try { System.out.print(“Enter file name: ”); String name = kbd.nextLine(); fin = new Scanner(new File(name)); } catch (FileNotFoundExceptionfnf) { System.out.println(“Not found! Try again.”); } } // read from the file using fin down here

  27. Scanner Declared Outside Loop • We will need the Scanner fin after the loop • declare it before the loop  use it after • declare in loop  can’t use it after • same applies to try block! • initialize fin to null • means there is no Scanner here • create new Scanner inside loop • assign to fin • if it works, fin will not be null (loop ends) • if it doesn’t, fin will still be null (loop will continue)

  28. Give Three Chances • Use a count-controlled loop + break Scanner fin = null; for (inti = 0; i < 3; i++) { try { System.out.print(“Enter file name: ”); fin = new Scanner(new File(kbd.nextLine())); break; // exit from the loop } catch (FileNotFoundExceptionfnf) { System.out.println(“Can’t find that file!”); } } if (fin == null) { System.exit(1); // add error msg} // read from the file using fin down here

  29. Count Control + break • For loop  user gets only 3 chances • try-catch in case user gives bad file name • error message printed and loop continues • if no exception continues in try-block body • break command  loop ends (even if user hasn’t taken all three chances) • Need to check after loop if fin is still null • user took three chances, but no good file given • print error message and exit program

  30. Use a Default File • If user’s named file doesn’t exist, use a name hard-coded into the program Scanner fin = null; try { System.out.print(“Enter file name: ”); fin = new Scanner(new File(kbd.nextLine())); } catch (FileNotFoundExceptionfnf) { fin = new Scanner(new File(“DefaultData.txt”)); } // read from the file using fin down here

  31. But What if That Doesn’t Work? • If can’t open default file, program will crash • it’s not in a try block! • So add the try block! it’s just fine! Scanner fin = null; try { System.out.print(“Enter file name: ”); fin = new Scanner(new File(kbd.nextLine())); } catch (FileNotFoundExceptionfnf) { try { fin = new Scanner(new File(“DefaultData.txt”)); } catch(FileNotFoundExceptionfnf) {System.exit(1);} }

  32. Exercise • Revise this code to return Earth (code = 0 and distance = 149.6) if file not found • don’t open a different file; return a different Planet! public Planet ReadPlanetFromFile() throws FileNotFoundException { Scanner fin = new Scanner(new File(“SecretPlanet.txt”)); String aName = fin.nextLine(); intaCode = fin.nextInt(); double aDist = fin.nextDouble(); fin.close(); return new Planet(aName, aDist, aCode); }

  33. Catching Different Exceptions • More than one thing could go wrong • at input prompt, type ctrl-D (mac or unix) or ctrl-Z ctrl-Z enter (Windows) • not the same as an InputMismatchException • our catch block won’t catch it Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:838) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextDouble(Scanner.java:2387) at SumNumbers.main(SumNumbers.java:22)

  34. Catching Different Exceptions • Can have more than one catch block • each has a different exception it catches try { … } catch(InputMismatchExceptionime) {…} catch(NoSuchElementExceptionnse) {…} • if an exception is thrown, it goes to the matching catch block • if no matching block, it keeps going • until it is caught, or until it gets out the top (crash!) see CatchExceptions.java

  35. Catching Different Exceptions while (num >= 0.0) { sum += num; try { num = kbd.nextDouble(); } catch(InputMismatchExceptionime) { System.err.println("Ignoring bad input!"); kbd.next(); // ignore one word num = 0.0; // to prevent messing up sum } catch(NoSuchElementExceptionnse) { break; // quietly leave the loop } } see CatchExceptions.java

  36. Multiple try-catch Blocks • Can have as many try-catch blocks as you need in any program (or method) • Can go anywhere other controls can go • (even inside other try or catch blocks) • Other controls can go inside them • inside the try; inside the catch • Might want to let one method throw the exception and another one catch it

  37. Catching Some, Throwing Others • Sum numbers from files • repeat until file-not-found exception occurs • Have a function to do the file i/o • catches InputMismatchException • to skip non-numeric input (but keep going) • declares FileNotFoundException • so main can catch it • main catches the FileNotFoundException • pops it out of an infinite loop

  38. SumManyFiles.java (part 1) • See the full program on-line public static void main(String[] args) { try { while (true) { // deliberately infinite loop! System.out.print("Enter file name: "); name = kbd.nextLine(); sum = sumThisFile(name); // throws FNFE System.out.println("The sum of all the numbers in " + name + " is " + sum + ".\n"); } } catch (FileNotFoundExceptionfnf) {} }

  39. SumManyFiles.java (part 2) • See the full program on-line public static double sumThisFile(String name) throws FileNotFoundException{ Scanner fin = new Scanner(new File(name)); // throws FNFE double sum = 0.0; while (fin.hasNext()) { try { double num = fin.nextDouble(); sum += num; } catch (InputMismatchExceptionime) { fin.next(); } } return sum; }

  40. Questions?

More Related