Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 14 Throwing Custom Exceptions

Similar presentations


Presentation on theme: "Lecture 14 Throwing Custom Exceptions"— Presentation transcript:

1 Lecture 14 Throwing Custom Exceptions
D&D 11 Date

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

3 Throwing an exception Throwing exceptions Custom exceptions finally
Notes Summary try { if (1 > 0) { throw new java.util.InputMismatchException(); } System.out.println("We never get here."); catch (java.util.InputMismatchException e) { System.out.println("Caught it!"); 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 InputMismatchException from the java.util package. Note that there is no actual input mismatch here – we’re throwing the exception arbitrarily. Normally, we use this mechanism to throw our own custom-made exceptions.

4 Re-throwing an exception
Throwing exceptions Custom exceptions finally Notes Summary try { if (1 > 0) { throw new java.util.InputMismatchException(); } System.out.println("We never get here."); catch (java.util.InputMismatchException e) { System.out.println("Caught it!"); throw e; 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.

5 Override of Exception’s getMessage() method
A custom exception Throwing exceptions Custom exceptions finally Notes Summary public class TemperatureException extends Exception { private double degrees; public TemperatureException(double degrees) { this.degrees = degrees; } public String getMessage() { return "The temperature (" + degrees + "C) isn't in the normal range."; public double getDegrees() { return degrees; Override of Exception’s getMessage() method New method 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 instance, which an exception handler can access.

6 A custom exception Throwing exceptions Custom exceptions finally Notes Summary public class TemperatureException extends Exception { private double degrees; public TemperatureException(double degrees) { this.degrees = degrees; } public String getMessage() { return "The temperature (" + degrees + "C) isn't in the normal range."; public double getDegrees() { return degrees; 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 instance, which an exception handler can access.

7 A custom exception Throwing exceptions Custom exceptions finally Notes Summary import java.util.Scanner; public class MedicalThermometer { public void measure() throws TemperatureException { Scanner s = new Scanner(System.in); System.out.println("Please enter patient temperature:"); double degrees = s.nextDouble(); if (degrees > 43 || degrees < 14) { throw new TemperatureException(degrees); } if (degrees >= 38) { System.out.println("Fever!"); else if (degrees < 35) { System.out.println("Hypothermia!"); else System.out.println("Normal."); This class may throw a TemperatureException 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. We do that by adding a throws clause to the method.

8 A custom exception Throwing exceptions Custom exceptions finally Notes Summary public class TestPatient { public static void main(String[] args) { MedicalThermometer t = new MedicalThermometer(); try { t.measure(); } catch (TemperatureException e) { System.out.println("Patient dead: " e.getDegrees() + " degrees!"); catch (Exception e) { System.out.println("Not a temperature!"); Handling the TemperatureException thrown by the measure() method in MedicalThermometer. Note that we also catch a general exception here. Why? And why don’t we need to mention this in the measure() method?

9 finally Throwing exceptions Custom exceptions finally Notes Summary
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 powerOn = true; public void heat(int seconds) { powerOn = true; try { degrees += seconds; // one degree per second if (degrees > 100) { throw new TemperatureException(degrees); } System.out.println("Heated to " + degrees + " degrees"); catch (TemperatureException e) { System.out.println("Overheating!"); finally { powerOn = false; public void getKettleStatus() { System.out.println(powerOn ? "Kettle on" : "Kettle off");

10 Boiling the kettle Throwing exceptions Custom exceptions finally Notes Summary public class BoilKettle { public static void main(String[] args) { Kettle k = new Kettle(); // Water k.heat(60); k.getKettleStatus(); k.heat(30); } 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.

11 Exception notes Throwing exceptions Custom exceptions finally Notes
Summary 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. 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. 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. Validation allows you to handle such situations in a way you control – as opposed to leaving it to your code to do… whatever!

12 What do we know Throwing exceptions Custom exceptions finally Notes
Summary 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. We can also create our own exception classes, instantiate and throw them. 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). 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 whether there is an exception or not.

13 Resources Throwing exceptions Custom exceptions finally Notes Summary
D&D Chapter 11

14 Next Lecture Basic GUI programming (Chapter 12)


Download ppt "Lecture 14 Throwing Custom Exceptions"

Similar presentations


Ads by Google