Lecture 14 Throwing Custom Exceptions DD 11 Date














- Slides: 14

Lecture 14 Throwing Custom Exceptions D&D 11 Date

Goals By the end of this lesson, you should 1. Know how to throw or re-throw exceptions 2. Be able to write your own subclasses of Exception and throw them 3. Be able to write methods that throw exceptions but do not handle them Comp. Sci 230: 2017 2

Throwing an exception 1. Throwing exceptions 2. Custom exceptions 3. finally try { if (1 > 0) { throw new java. util. Input. Mismatch. Exception(); } System. out. println("We never get here. "); } catch (java. util. Input. Mismatch. Exception e) { System. out. println("Caught it!"); } 4. Notes 5. Summary We can throw (trigger) exceptions of any type with the throw keyword, followed by the Exception object that we want to throw. In this case, we create the Exception object on the spot with new, and the subclass we actually instantiate is an Input. Mismatch. Exception from the java. util package. Note that there is no actual input mismatch here – we’re throwing the exception arbitrarily. Comp. Sci 230: 2017 Normally, we use this mechanism to throw our own custom-made exceptions. 3

Re-throwing an exception 1. Throwing exceptions try { if (1 > 0) { throw new java. util. Input. Mismatch. Exception(); } System. out. println("We never get here. "); } catch (java. util. Input. Mismatch. Exception e) { System. out. println("Caught it!"); throw e; } 2. Custom exceptions 3. finally 4. Notes 5. Summary } catch (Exception e) { System. out. println("And caught it again!"); } We can re-throw exceptions in the catch block if we’re not completely done with handling them. This lets us do some of the handling locally while we can still signal to an event handler further up the calling chain. Comp. Sci 230: 2017 4

A custom exception 1. Throwing exceptions public class Temperature. Exception extends Exception { private double degrees; 2. Custom exceptions public Temperature. Exception(double degrees) { this. degrees = degrees; Override of Exception’s } get. Message() method 3. finally public String get. Message() { return "The temperature (" + degrees + "C) isn't in the normal range. "; } 4. Notes 5. Summary public double get. Degrees() { return degrees; } New method } Comp. Sci 230: 2017 We declare custom exception classes as a subclass of Exception, like any other Java class that extends a superclass. A constructor lets us pass parameters to add to the exception 5 instance, which an exception handler can access.

A custom exception 1. Throwing exceptions public class Temperature. Exception extends Exception { private double degrees; 2. Custom exceptions public Temperature. Exception(double degrees) { this. degrees = degrees; } 3. finally public String get. Message() { return "The temperature (" + degrees + "C) isn't in the normal range. "; } 4. Notes 5. Summary public double get. Degrees() { return degrees; } } Comp. Sci 230: 2017 We declare custom exception classes as a subclass of Exception, like any other Java class that extends a superclass. A constructor lets us pass parameters to add to the exception 6 instance, which an exception handler can access.

A custom exception 1. Throwing exceptions 2. Custom exceptions 3. finally 4. Notes 5. Summary import java. util. Scanner; public class Medical. Thermometer { public void measure() throws Temperature. Exception { Scanner s = new Scanner(System. in); System. out. println("Please enter patient temperature: "); double degrees = s. next. Double(); if (degrees > 43 || degrees < 14) { throw new Temperature. Exception(degrees); } if (degrees >= 38) { System. out. println("Fever!"); } else if (degrees < 35) { System. out. println("Hypothermia!"); } else System. out. println("Normal. "); } } Comp. Sci 230: 2017 This class may throw a Temperature. Exception in its measure() method. Because it doesn’t handle the exception, we need to signal to the calling code that it needs to be handled there. 7 We do that by adding a throws clause to the method.

A custom exception 1. Throwing exceptions public class Test. Patient { public static void main(String[] args) { Medical. Thermometer t = new Medical. Thermometer(); try { t. measure(); } catch (Temperature. Exception e) { System. out. println("Patient dead: " + e. get. Degrees() + " degrees!"); } catch (Exception e) { System. out. println("Not a temperature!"); } } 2. Custom exceptions 3. finally 4. Notes 5. Summary } Handling the Temperature. Exception thrown by the measure() method in Medical. Thermometer. Note that we also catch a general exception here. Why? And why don’t we need to mention this in the measure() method? Comp. Sci 230: 2017 8

finally 1. Throwing exceptions 2. Custom exceptions A quick mention here of the finally block. A finally block always executes when a try block exits – regardless of whether the try block ran successfully or whether an exception got thrown. public class Kettle { private int degrees = 20; private boolean power. On = true; public void heat(int seconds) { power. On = true; try { degrees += seconds; // one degree per second if (degrees > 100) { throw new Temperature. Exception(degrees); } System. out. println("Heated to " + degrees + " degrees"); } catch (Temperature. Exception e) { System. out. println("Overheating!"); } finally { power. On = false; } } 3. finally 4. Notes 5. Summary public void get. Kettle. Status() { System. out. println(power. On ? "Kettle on" : "Kettle off"); } } Comp. Sci 230: 2017 9

Boiling the kettle 1. Throwing exceptions public class Boil. Kettle { public static void main(String[] args) { Kettle k = new Kettle(); // Water k. heat(60); k. get. Kettle. Status(); k. heat(30); k. get. Kettle. Status(); } 2. Custom exceptions 3. finally 4. Notes 5. Summary } This is a bit of a toy example. In most cases, we use finally to ensure that resources such as files, network connections, streams, etc. are closed properly and not left hanging in an undefined state when an exception gets thrown. Comp. Sci 230: 2017 10

Exception notes 1. Throwing exceptions Exceptions are a good mechanism to flag input data that does not pass validation: Normally, regular input data should pass validation, so if it doesn’t pass, then this should be an exception, not the rule. 2. Custom exceptions That said, it is good software engineering and security practice to allow for input data that may fail validation. This is especially so if the source of the input data is a user or system that you have no control over. 3. finally Input data that fails validation could be supplied by: • A malicious user trying to subvert your system • Another system whose data output has changed, e. g. , as a result of a configuration change or software upgrade, and whose format is no longer compatible with yours. 4. Notes 5. Summary Validation allows you to handle such situations in a way you control – as opposed to leaving it to your code to do… whatever! Comp. Sci 230: 2017 11

What do we know 1. Throwing exceptions 1. We don’t need to rely on built-in exceptions thrown by code that comes with Java – we can throw any exception ourselves in our own code. 2. Custom exceptions 2. We can also create our own exception classes, instantiate and throw them. 3. finally 4. Notes 5. Summary 3. If we instantiate and throw our own exception without handling it in the method in which we throw it, we must add a throws clause to the method signature to indicate to the Java compiler that the method may terminate via exception rather than in the normal way (return). 4. The finally clause is an addition to the try-catch blocks we’ve seen so far and contains statements that we always want to have executed regardless of whethere is an exception or not. Comp. Sci 230: 2017 12

Resources 1. Throwing exceptions 2. Custom exceptions D&D Chapter 11 https: //docs. oracle. com/javase/tutorial/essential/exceptions/ind ex. html 3. finally 4. Notes 5. Summary Comp. Sci 230: 2017 13

Next Lecture Basic GUI programming (Chapter 12)