Download presentation
Presentation is loading. Please wait.
1
Throwing, Catching Defining
Exceptions Throwing, Catching Defining
2
Outcomes Find the exception that crashed a program
find where it happened in your code Write a try-catch block to catch exceptions your program might throw Design and place try-catch blocks so your program recovers gracefully Create your own Exception class
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 One method throws the exception
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 methods 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
Exception Hierarchy Exception IOException RuntimeException
EOFException ClassCastException FileNotFoundException ConcurrentModificationException IndexOutOfBoundsException IllegalArgumentException ArrayIndexOutOfBoundsException NoSuchElementException StringIndexOutOfBoundsException NullPointerException InputMismatchException
12
Throwing Exceptions Throw an exception when errors happen
and you can’t deal with it properly Throw an appropriate type of exception illegal argument IllegalArgumentException out of bounds IndexOutOfBoundsException bad time for request IllegalStateException If necessary, make your own exception type extend RuntimeException
13
Setters Throwing Exceptions
Client tries to set property to illegal value length & width of recatngle must be >= 0 public void setWidth(double newWidth) { // object to negative widths if (newWidth < 0) { String message = "Illegal width: " + newWidth; throw new IllegalArgumentException(message); } // new width OK – make the change width = newWidth;
14
The throw Command Command to throw an exception is throw
throw new IllegalArgumentException(message); Exception to throw usually created there Exception constructor given a message String message = "Illegal width: " + newWidth; message is printed out if program crashes
15
Exercise Rewrite the following constructor to throw an exception if either argument is negative public Rectangle(double reqWidth, double reqHeight) { if (reqWidth >= 0) { width = reqWidth; } else { width = 0; } if (reqHeight >= 0) { height = reqHeight; height = 0;
16
Catching Exceptions try-catch block
… // code that may throw an exception } catch(ExceptionClass exceptionObject) { … // code to handle the exception } Try to do this, and if something goes wrong, do this to deal with it
17
Catching Exceptions For catching InputMismatchException
inside the number-reading loop try { num = kbd.nextDouble(); // may throw an exception kbd.nextLine(); } catch(InputMismatchException ime) { System.out.println(“That’s not a number!”); break; // exit from loop Note: it’s a parameter! see CatchInputMismatch.java
18
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
19
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
20
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)
21
When an Exception Occurs…
Code in try block gets skipped right out from where the exception occurred // read an integer and save it in num num = kbd.nextInt(); // skip the rest of the input line kbd.nextLine(); if next thing isn’t an int, NONE of that happens doesn’t read an integer (no integer there to be read!) doesn’t save anything in num (num unchanged!) doesn’t skip rest of line
22
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?
23
What Do I Want to Do? Reading int values; non-int value entered
try { num = kbd.nextInt(); } catch (InputMismatchException ime) { end the loop? break; skip invalid data? kbd.next(); } but if you skip, what else might go wrong?
24
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?
25
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
26
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 (InputMismatchException ime) {} System.out.println(“The sum is ” + sum); What does the catch block do here?
27
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 (InputMismatchException ime) { System.out.println(“The sum is ” + sum); NOTE: You don’t need to add any code. Just move a piece of it!
28
Our Own Exception Classes
Usually use a built-in exception class e.g. IllegalArgumentException Can create our own exception classes if none of the available ones is exactly right or want to distinguish different problems We will extend RuntimeException extending Exception leads to complications or some other suitable RuntimeException
29
Our Own Exception Class
NotEnufMilkException represents not having enuf milk public class NotEnufMilkException extends RuntimeException { public NotEnufMilkException() { super(“Not enuf milk!”); } public NotEnufMilkException(String message) { super(message); see NotEnufMilkException.java
30
Our Own Exception Classes
Name ends with Exception just so we’re clear about what it is! Consists of two constructors default constructor calls super with a default message (or no message) super("Not enuf milk!"); constructor with String parameter calls super with that String super(message);
31
Another Exception Class
NotEnufCookiesException public class NotEnufCookiesException extends RuntimeException { public NotEnufCookiesException() { super(“Not enuf cookies!”); } public NotEnufCookiesException(String message) { super(message); What exactly is the difference between this exception class definition and the previous one? see NotEnufCookiesException.java
32
Catching Different Exceptions
Can have more than one catch block each has a different exception it catches try { … } catch(NotEnufMilkException e) {…} catch(NotEnufCookiesException e) {…} 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 RoomReports.java
33
More Constructors Every Exception class should have constructors for () and (String) every built in Exception class does Can add more of our own assignment number is an int public IllegalAssignmentException(int asgn) { super("No such assignment: " + asgn); } need to call super(String) – no super(char)!
34
Questions?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.