About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Similar documents
About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

ECE 122. Engineering Problem Solving with Java

CS 3 Introduction to Software Engineering. 3: Exceptions

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Fundamentals of Object Oriented Programming

More on Exception Handling

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

BBM 102 Introduction to Programming II Spring Exceptions

More on Exception Handling

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Internal Classes and Exceptions

C16b: Exception Handling

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Data Structures. 02 Exception Handling

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Exceptions. CSC207 Winter 2017

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Errors and Exceptions

Programming II (CS300)

Lecture 19 Programming Exceptions CSE11 Fall 2013

What are Exceptions?

Exception-Handling Overview

ITI Introduction to Computing II

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

ITI Introduction to Computing II

BBM 102 Introduction to Programming II Spring 2017

CS112 Lecture: Exceptions and Assertions

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exceptions and Error Handling

Programming II (CS300)

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Exceptions - Example. Exceptions - Example

CSCI 261 Computer Science II

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions. What exceptional things might our programs run in to?

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

National University. Faculty of Computer Since and Technology Object Oriented Programming

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Correctness and Robustness

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

CSE 331 Software Design & Implementation

EXCEPTIONS. Java Programming

CS159. Nathan Sprague

Exceptions in Java

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 14. Exception Handling and Event Handling ISBN

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Exceptions Handling Errors using Exceptions

COMP1008 Exceptions. Runtime Error

EXCEPTION HANDLING. Summer 2018

Introduction to Software Design

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Programming Languages and Techniques (CIS120)

COMP-202 Unit 9: Exceptions

Introduction to Java. Handout-3a. cs402 - Spring

Introduction to Computer Science II CS S-22 Exceptions

Full file at Chapter 2 - Inheritance and Exception Handling

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Object Oriented Programming. Week 7 Part 1 Exceptions

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

14. Exception Handling

Typecasts and Dynamic Dispatch. Dynamic dispatch

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Program Correctness and Efficiency. Chapter 2

17. Handling Runtime Problems

Chapter 13 Exception Handling

Programming Languages and Techniques (CIS120e)

Java Errors and Exceptions. Because Murphy s Law never fails

CMSC 202. Exceptions

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Exceptions. Examples of code which shows the syntax and all that

Introduction Unit 4: Input, output and exceptions

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Object Oriented Programming

Transcription:

Exceptions Revised 24-Jan-05 CMPUT 115 - Lecture 4 Department of Computing Science University of Alberta About This Lecture In this lecture we will learn how to use Java Exceptions to handle unusual program conditions. D. Szafron, C. Jones 2003 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package CMPUT 115 - Lecture 4 Slide 2 Outline When things go wrong Throwables, Errors and Exceptions Throwing exceptions Catching exceptions Defining your own exception classes When things go wrong In the last lecture, we learned about pre/post conditions, and assertions. But what if these fail? Java: originally developed for writing software embedded in specialized devices (cell phones, hand-held computers, appliances etc.) Such software must be able to handle unusual situations and manage appropriately when things go wrong CMPUT 115 - Lecture 4 Slide 3 CMPUT 115 - Lecture 4 Slide 4 Reacting to errors Handling Unusual Situations What if the user enters a word instead of an integer? We try to pop an empty stack? In many languages, the programmer is solely responsible for dealing with errors no help from the language itself we try to divide by zero? We try to read from a file which doesn t exist? We try to access a remote location but the network is down? Should the program produce bad output, or should it crash, or should it try to recover? Code must be written to help identify kinds of errors and how to deal with them convoluted code! Often, methods will return an unusual value such as 1 or null to indicate a failure often difficult to interpret! Java provides some helpful mechanisms to assist us CMPUT 115 - Lecture 4 Slide 5 CMPUT 115 - Lecture 4 Slide 6 1

Exceptions & Errors Java has 2 classes for modeling problems: Error Exception Errors Java.lang.Error models serious, unrecoverable errors such as fatal linkage problems virtual machine errors These errors are not handled and coped with, they usually terminate execution Note that both are subclasses of Throwable Not as common as Exceptions CMPUT 115 - Lecture 4 Slide 7 CMPUT 115 - Lecture 4 Slide 8 What is an Exception? An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions - Sun Microsystems web site tutorial Not as serious as system errors maybe we can try to recover from them, or at least handle them gracefully Why use exceptions? As we will see in this lecture, the advantages of using exceptions include: separating error-handling code from regular code deferring decisions about how to respond to exceptions providing a mechanism for specifying the different kinds of exceptions that can arise in our program to bear these points in mind as we discuss this material CMPUT 115 - Lecture 4 Slide 9 CMPUT 115 - Lecture 4 Slide 10 The Exception Mechanism Propagating exceptions When a method wants to signal that a problem has arisen (e.g. a precondition is violated) it throws an exception instead of returning normally. The exception goes to the method that called the method that threw the exception. That method can either Catch (handle) the exception Propagate the exception to the method that called it So an exception will bubble up the call stack until it reaches a method with a suitable handler, or it propagates through the main( ) method (the first method on the call stack) If it is not caught by any method the exception is treated like an error: the stack frames are displayed and the program terminates CMPUT 115 - Lecture 4 Slide 11 CMPUT 115 - Lecture 4 Slide 12 2

Example: Throwing an Exception public Ratio(int top, int bottom) throws Exception{ /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom if (bottom == 0) throw new Exception("Denominator must not be 0"); this.numerator = top; this.denominator = bottom; Throwing Exceptions What can be thrown? Any instance of Throwable or its sublcasses, including Error and Exception Instances of our own specialized exception classes How do we do it? Create an instance, & throw it! throw new Exception( ); throw new Exception( Explanatory message ); CMPUT 115 - Lecture 4 Slide 13 CMPUT 115 - Lecture 4 Slide 14 Throws clause in method signature The throws clause tells the compiler that a method is a potential source of that type of exception, and that any method that invokes it must be able to deal with it A method must include a throws clause in its signature if it throws an exception itself it might propagate the exception (because it calls another method that might throw an exception that this method cannot catch/handle) public Ratio add(ratio other) throws Exception { /* pre: other is non-null The throws Clause post: return new fraction - the sum of this & other Assert.pre(other!= null, "Other must not be null"); return new Ratio(this.numerator * other.denominator + this.denominator * other.numerator, this.denominator * other.denominator); CMPUT 115 - Lecture 4 Slide 15 CMPUT 115 - Lecture 4 Slide 16 Throws clause for the main method The signature of the main method must contain a throws clause for any exception that might be thrown by any method it calls (or methods they call, etc.) and not caught. public static void main(string args[])throws Exception{ Ratio r = new Ratio(1,1); // r == 1.0 r = new Ratio(1,2); // r == 0.5 r.add(new Ratio(1,3)); // r still 0.5 r = r.add(new Ratio(1,4)); // r == 0.75 System.out.println(r.value()); // 0.75 printed r = new Ratio(1, 0); // should be an exception Exceptions not Caught If an exception is not caught by any handler, the exception behaves like an error: the program is halted, a message is displayed, and the stack frames are displayed: 0.75_exceptionOccurred: java.lang.exception (Denominator must not be 0) java.lang.exception: Denominator must not be 0 at Ratio.<init>(Ratio.java) at RatioTest.main(RatioTest.java) at com.apple.mrj.jmanager.jmstaticmethoddispatcher.run(jmawtcontextimpl.java) at java.lang.thread.run(thread.java) CMPUT 115 - Lecture 4 Slide 17 CMPUT 115 - Lecture 4 Slide 18 3

Checked/Unchecked Exceptions Diagram Unchecked exceptions: Any exception that is a subclass of java.lang.runtimeexception java.lang.error Not a compile-time error to ignore the possibility of these exceptions we are free to catch them if we want to, but if we don t we re not required to include a throws clause Throwable Exception RuntimeException Any other subclass Error Any subclass Checked exceptions: All other kinds of exceptions must include a throws clause if an exception may occur somewhere inside it Any subclass Any subclass unchecked checked CMPUT 115 - Lecture 4 Slide 19 CMPUT 115 - Lecture 4 Slide 20 Java s Exception handling When we write a piece of code that we know might produce an exception and we want to catch (handle) the exception, we encapsulate that code in a try block. If no exception is thrown by code within the try block (or the methods that are called within the try block), the code executes normally. If an exception arises in the try block the execution of the try block terminates execution immediately and a catch-clause is sought to handle the exception. Either 1. An appropriate catch clause is found, in which case it is executed, or 2. The exception is propagated to the calling method CMPUT 115 - Lecture 4 Slide 21 Example: try-catch public static void main(string args[])throws Exception { Ratio r; r = new Ratio(1, 0); catch (Exception anexception) { System.out.println(anException); r = new Ratio(); // initializes to 0/1 System.out.println( The value is +r.value()); java.lang.exception: Denominator must not be 0 The value is 0.0 can we removed this? CMPUT 115 - Lecture 4 Slide 22 Catch clause A catch clause is associated with a particular try block. It will only be used for exceptions that arise within that try block. A catch clause has one parameter the type of this parameter is the type of the exception that this clause can handle. A try statement can have one or more catch clauses, to catch different types of exceptions. Pause for thought Why not just put the exception-handling code in the method where the exception is thrown instead of throwing the exception? Because, different callers may want to handle the same exception differently. For example, the previous segment binds the variable r to a zero Ratio. A different segment might want to bind the variable r to null if an exception occurs. CMPUT 115 - Lecture 4 Slide 23 CMPUT 115 - Lecture 4 Slide 24 4

block Examples // code inside the try block // no catch clause any exceptions that arise in the try block // will propagate to the calling method // code within the try block catch (Exception anexception) { // code that handles any Exception that arises in the try block CMPUT 115 - Lecture 4 Slide 25 Multiple Catch Clauses readfromfile( data.txt ); // readfromfile() might generate an exception catch (FileNotFoundException e) { // deal with file_not_found error catch (IOException e) { // deal with errors that occur while reading from file catch (Exception e) { // deal with all other errors what if we put the Exception clause at the top, in front of FileNotFoundException? CMPUT 115 - Lecture 4 Slide 26 Java s built-in exception classes Common run-time problems you ve probably seen already: ArrayIndexOutOfBoundsException NullPointerException ArithmeticException NumberFormatException ClassCastException Java provides more than 2 dozen Exceptions to model different kinds of errors and we can write our own too! User-defined Throwable Classes You can define your own Exception subclasses. This allows you to conditionally match only the Exceptions that you want to match. You can also define your own Error subclasses, although this is unusual because normally the exceptions you define will not be unrecoverable. CMPUT 115 - Lecture 4 Slide 27 CMPUT 115 - Lecture 4 Slide 28 Example: User-defined Exception To define a new type of exception, simply create a subclass of Exception. It will inherit the property of being throwable For example, if we wanted to define our own exception called ZeroDenominator we would define a class called ZeroDenominator in a file called ZeroDenominator.java It could be as simple as this one line public class ZeroDenominator extends Exception{ Throwing a User-defined Exception public Ratio(int top,int bottom) throws ZeroDenominator { /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom if (bottom == 0) throw new ZeroDenominator(); this.numerator = top; this.denominator = bottom; CMPUT 115 - Lecture 4 Slide 29 CMPUT 115 - Lecture 4 Slide 30 5

Catching a User-defined Exception public static void main(string args[]) { Ratio r; r = new Ratio(1, 0); catch (ZeroDenominator anexception) { r = new Ratio(); // initializes to 0/1 System.out.println( The value is +r.value()); Multiple Constructors public class ZeroDenominator extends Exception { public ZeroDenominator(String msg) { super("\nzerodenominator with message " + msg); public ZeroDenominator() { super("\nzerodenominator with no message ); The value is 0.0 CMPUT 115 - Lecture 4 Slide 31 CMPUT 115 - Lecture 4 Slide 32 finally clause If you want to execute some code whether an exception was raised or not, you can use the optional finally clause Guaranteed to be executed, no matter why we leave the try block It is optional you don t have to have one. Why use finally? The finally clause is useful if you want to perform some kind of clean up operations before exiting the method example: closing down a stream/resource Also avoids duplicating code in each catch clause CMPUT 115 - Lecture 4 Slide 33 CMPUT 115 - Lecture 4 Slide 34 Full Semantics of try-catch-finally If an expression in the try block throws an exception: the rest of the code in the try block is skipped. If the exception matches the first catch clause the code in its catch block is run the code in the finally clause is run. the rest of the catch clauses are ignored. the rest of the code in the method is run. If the exception does not match the first catch clause, similar actions are taken for the first matching catch clause. CMPUT 115 - Lecture 4 Slide 35 Full Semantics of try-catch-finally If the exception does not match any catch clause the code in the finally clause is run all other code in the method is abandoned the exception is thrown to the calling method start looking for some other portion of code that will catch and handle the exception If no exception is thrown at all all code in the try block is executed the code in the finally clause is run normal code in the method following finally is run CMPUT 115 - Lecture 4 Slide 36 6

Possible Execution Paths (1) Possible Execution Paths (2) 1. No exception occurs 1. Execute the try block 2. Execute the finally clause 3. Execute the rest of the method 1. Exception occurs and is caught 1. Execute the try block until the first exception occurs 2. Execute the first catch clause that matches the exception 3. Execute the finally clause 4. Execute the rest of the method Catch Rest of method Rest of method CMPUT 115 - Lecture 4 Slide 37 CMPUT 115 - Lecture 4 Slide 38 Possible Execution Paths (3) 3. Exception occurs and is not caught 1. Execute the try block until the first exception occurs 2. Execute the finally clause 3. Propagate the exception to the calling method Throw back Do we deed a different logic? What if we wish to have a cleaner execution Catch Catch Rest of method CMPUT 115 - Lecture 4 Slide 39 Q: Can we have either TRY-FINAALY or CATCH-FINALLY? CMPUT 115 - Lecture 4 Slide 40 Example: finally & Multiple catches 1 Example: finally & Multiple catches 2 Use a NumberFormatException in the Ratio constructor to signal a zero denominator: public Ratio(int top, int bottom) throws NumberFormatException{ /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom if (bottom == 0) throw new NumberFormatException( "Denominator must not be 0"); this.numerator = top; this.denominator = bottom; CMPUT 115 - Lecture 4 code based on Bailey Slide pg. 9 41 Consider a divide method in the class Ratio: public Ratio divide(ratio other) throws Exception { /* pre: other is non-null pre: other is not zero post: return new fraction - the division of this and other if (other == null) throw new NullPointerException(); else if (other.numerator == 0) throw new ArithmeticException(); else return new Ratio(this.numerator*other.denominator, this.denominator*other.numerator); CMPUT 115 - Lecture 4 code based on Bailey Slide pg. 9 42 7

Example: finally & Multiple catches 3 Example: finally & Multiple catches 4 Consider some static method in a class called Tester, that calls the divide method and catches all but one exception (the NumberFormatException): private static void calldivide(ratio top, Ratio bottom) throws Exception{ /* Compute the division of top by bottom and report the answer. If top is null then change it to an invalid ratio 1/0 to generate a NumberFormatException that won't be caught. Catch the other exceptions: bottom is zero or bottom is null. Ratio answer; answer = null; if (top == null) top = new Ratio(1, 0); answer = top.divide(bottom); catch (ArithmeticException anexception) { System.out.println("Arithmetic Except: no div by 0"); answer = new Ratio(); catch (NullPointerException anexception) { System.out.println("NullPointerExcept: no div by null"); answer = new Ratio(); finally { System.out.println(" the answer: " + answer); // rest skipped for NumberFormatException since not caught System.out.println("End method answer: + answer.value()); CMPUT 115 - Lecture 4 code based on Bailey Slide pg. 943 CMPUT 115 - Lecture 4 code based on Bailey Slide pg. 944 Example: finally & Multiple catches 5 main method illustrating exception handling: public static void main(string args[]) { Tester.callDivide(new Ratio(1, 2), new Ratio(3,4)); // should work Tester.callDivide(new Ratio(1, 2), new Ratio(0,4)); // ArithmeticException caught in calldivide() Tester.callDivide(new Ratio(1, 2), null); // NullPointerException caught in calldivide() Tester.callDivide(null, new Ratio(3,4)); // NumberFormatException NOT caught in calldivide() catch (Exception anexception) { System.out.println("NumberFormatException not caught by calldivide()"); CMPUT 115 - Lecture 4 code based on Bailey Slide pg. 945 8