Lecture 14 Throwing Custom Exceptions

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
COMP 121 Week 5: Exceptions and Exception Handling.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exception handling Dealing with life’s little surprises.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
CS1101: Programming Methodology Aaron Tan.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Exception Handling. Outline What is an Exception How to use exceptions catch ing throw ing Extending the Exception class Declaring using the throws clause.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Java Exceptions a quick review….
Chapter 14 – Exception Handling
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Java Programming Language
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Multithreading in Java
Chapter 14: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Exceptions & exception handling
ATS Application Programming: Java Programming
Exceptions & exception handling
Java Programming Language
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Fundamental Error Handling
Part B – Structured Exception Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Lecture 11 Objectives Learn what an exception is.
Chapter 9 Exception Handling
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Exception Handling Contents
Exceptions 10-May-19.
Why do we need exceptions?
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Java Chapter 5 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Lecture 14 Throwing Custom Exceptions D&D 11 Date

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

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.

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.

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.

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.

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.

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?

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");

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.

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!

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.

Resources Throwing exceptions Custom exceptions finally Notes Summary D&D Chapter 11 https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

Next Lecture Basic GUI programming (Chapter 12)