Java 20 -- Exceptions


Read D&D ch 11

ExceptionExamples.java
BadThingHappened.java


Classwork

Part A

1. Why would you want to set up a try block with more than one catch block? Give a specific example (you don't have to give code, just describe a situation).

2. You're writing a method public void report(Person aperson) which calls various methods for aperson. Of course, if aperson is null, you'll get a NullPointerException. Should you a) use a try-catch block around the calls, b) put a "throws" marker on your method, c) use an assertion, or d) something else (if so, what?) ?

3. JebsDiscountStream class has a discountReadLine() method that, if there is an exception in getting input, catches the exception itself, and returns the String, "none" rather than throwing an exception. Give an example of a case where using this would be a Very Bad Idea. (hint: you don't have to invent ways the method could be badly written outside the description just given)


Part B

Choose one of your (any group member) previous classes with at least two mutators that validate values before setting, at least one of which deals with an instance variable which is a number. (You may add validation to a mutator that did not previously have it, but only validation that makes sense in the context of the class).

Change the mutators so that instead of doing nothing on a bad value, they throw an IllegalArgumentException.

In a main, get values for each of those instance variables from a user and attempt to use the mutator. For each, keep making the user enter values until one doesn't trigger an exception.

Catch at least one other exception possible when getting these values from the user and setting them (hint: depending on how you do the input, InputMismatchException or NumberFormatException may be possible) Deliberately triggering a spurious NullPointerException or similar doesn't count, but you can be sloppy about input validation.

In the same class with the changed mutators, add at least one assertion that makes sense in context.