CS 3 Introduction to Software Engineering. 3: Exceptions

Similar documents
Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Programming II (CS300)

Chapter 14. Exception Handling and Event Handling ISBN

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

Assertions and Exceptions Lecture 11 Fall 2005

17. Handling Runtime Problems

Exceptions in Java

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

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

Programming II (CS300)

Exceptions and assertions

EXCEPTION HANDLING. Summer 2018

CS159. Nathan Sprague

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

COMP1008 Exceptions. Runtime Error

BBM 102 Introduction to Programming II Spring Exceptions

Object Oriented Programming

CSE 331 Software Design & Implementation

Programming Languages and Techniques (CIS120)

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

Object Oriented Programming

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

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

BBM 102 Introduction to Programming II Spring 2017

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

Chapter 13 Exception Handling

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

Designing Robust Classes

14. Exception Handling

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

Chapter 14. Exception Handling and Event Handling

Exception Handling Advanced Programming Techniques

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

Exception-Handling Overview

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

CS112 Lecture: Exceptions and Assertions

Errors and Exceptions

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

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

CS159. Nathan Sprague

CSE 143 Java. Exceptions 1/25/

Internal Classes and Exceptions

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Exceptions. CSC207 Winter 2017

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

Data Structures. 02 Exception Handling

C16b: Exception Handling

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

Exceptions and Design

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

Correctness and Robustness

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

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

Introductory Programming Exceptions and I/O: sections

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

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

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

CSCI 261 Computer Science II

ECE 122. Engineering Problem Solving with Java

Exceptions - Example. Exceptions - Example

ITI Introduction to Computing II

Lecture 12 Assertions & Exceptions

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

2.6 Error, exception and event handling

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

Contents. I Introductory Examples. Topic 06 -Exception Handling

Lecture 10 Assertions & Exceptions

ITI Introduction to Computing II

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

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

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

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

CS2: Debugging in Java

Chapter 12 Exception Handling

Java Loose Ends. 11 December 2017 OSU CSE 1

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

CSE 331 Software Design and Implementation. Lecture 12 Assertions & Exceptions

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Main concepts to be covered. Handling errors. Some causes of error situations. Not always programmer error. Defensive programming.

Exception Handling Generics. Amit Gupta

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

COSC Exception Handling. Yves Lespérance. Lecture Notes Week 10 Exception Handling

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

Program Correctness and Efficiency. Chapter 2

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

16-Dec-10. Consider the following method:

Title. Java Just in Time. John Latham. February 8, February 8, 2018 Java Just in Time - John Latham Page 1(0/0)

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

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

ASSERTIONS AND LOGGING

Object-Oriented Programming in the Java language

Transcription:

CS 3 Introduction to Software Engineering 3: Exceptions

Questions? 2

Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction 3

What are Exceptions? Control-flow mechanism for unusual situations. Thrown by methods/operators if no well-typed result makes sense. Caught by handlers installed by callers. Exception value (object) identifies the exceptional condition. In theory, doesn t have to correspond to an error. Lets method return to somewhere other than call site. Can provide escape hatch for deep recursion, nested loops. Textbook does this all over the place. But it s a bad idea! (Constructing exception objects is generally expensive.) (try-catch interferes with compiler optimizations, etc.) See online reading by Sestoft (2005). 4

Handling Exceptions try block catch (ExnType 1 x 1 ) catchblock1 catch (ExnType N x N ) catchblock N finally finallyblock If N > 0, finally part is optional. If block terminates with exn, execute first catchblock i (if any) such that exn has type ExnType i, binding exn to x i. If there is no such i, rethrow exn, possibly terminating method. Regardless of how block and/or catchblock i terminates (normal, exception, return, break), execute finallyblock. (This is not a complete set of rules look them up.) 5

Kinds of Exceptions In statement throw e; e must have type java.lang.throwable. Three kinds of Throwables: java.lang.exception: thrown by libraries or user code. FileNotFoundException, MalformedURLException. java.lang.runtimeexception: Subclass of Exception, handled specially. NullPointerException, ArithmeticExpression. java.lang.error: thrown by the JVM. NoClassDefFoundError, StackOverflowError. 6

What s s the Difference? Answer two ways: Treated differently by language. Used differently by convention. Language difference? Checked vs. unchecked. Checked = not Error, not RuntimeException. Method s throws clause must list all checked exns that might terminate method. Whether thrown explicitly with throw or by callees. Exceptions handled by method don t escape; no need to declare. 7

What s s the Difference? Answer two ways: Treated differently by language. Used differently by convention. Language difference? Checked vs. unchecked. Checked = not Error, not RuntimeException. Method s throws clause must list all checked exns that might terminate method. Whether thrown explicitly with throw or by callees. Exceptions handled by method don t escape; no need to declare. 8

What s s the Difference? Usage differences? Basic Rules: Errors thrown by VM for severe problems. RuntimeExceptions signal bugs in programs. Things which should not have happened. Checked Exceptions signal unusual conditions. Transient problems, like dropped net connections. User mistakes, like nonexistent filenames. Something a caller may not expect but must prepare for. Another Consideration: Checked exceptions can be a nuisance. (C# doesn t have them.) 9

What s s the Difference? Usage differences? Basic Rules: Errors thrown by VM for severe problems. RuntimeExceptions signal bugs in programs. Things which should not have happened. Checked Exceptions signal unusual conditions. Transient problems, like dropped net connections. User mistakes, like nonexistent filenames. Something a caller may not expect but must prepare for. Another Consideration: Checked exceptions can be a nuisance. (C# doesn t have them.) 10

Exceptions and Abstractions Procedures should document all exceptions they may throw (checked or not). /** Computes the factorial of an integer. * @param n * @return the factorial of n * @throws IllegalArgumentException if n < 0. */ int factorial(int n) { if (n < 0) { throw new IllegalArgumentException(); } } 11

Exceptions and Abstractions Non-Redundancy Principle: If some condition is documented to cause an exception, it is NOT necessary to prohibit it with a Requires clause. /** Computes the factorial of an integer. * <p> Requires: n >= 0 * @param n * @return n! */ /** Computes the factorial of an integer. * @param n * @return n! * @throws IllegalArgumentException if n < 0 */ 12

Exceptions and Abstractions Non-Redundancy Principle: If some condition is documented to cause an exception, it is NOT necessary to prohibit it with a Requires clause. /** Computes the factorial of an integer. * <p> Requires: n >= 0 * @param n * @return n! */ /** Computes the factorial of an integer. * @param n * @return n! * @throws IllegalArgumentException if n < 0 */ 13

Exceptions and Abstractions Non-Redundancy Principle: If some condition is documented to cause an exception, it is NOT necessary to prohibit it with a Requires clause. /** Computes the area of a triangle using Heron s Formula. * <p> Requires: a, b and c are all positive * * @return The area of a triangle with sides of lengths a, b and c. */ /** Computes the area of a triangle using Heron s formula. * * @return The area of a triangle with sides of lengths a, b and c. * @throws IllegalArgumentException if a <= 0 or b <= 0 or c <= 0. */ 14

Exceptions and Abstractions Sometimes have a choice: Requires specification, or check and throw exception? Two points of view: Defensive: Shorter Requires clauses are better. Check for bad conditions and throw exceptions. Passive-Aggressive : Too many exceptions make specifications confusing, too many checks make code confusing. Partial functions can be easier. Book (and I) favor a defensive approach: Catch errors as soon as possible. Fail gracefully when something goes wrong. 15

Exceptions and Abstractions Sometimes have a choice: Requires specification, or check and throw exception? Two points of view: Defensive: Shorter Requires clauses are better. Check for bad conditions and throw exceptions. Passive-Aggressive : Too many exceptions make specifications confusing, too many checks make code confusing. Partial functions can be easier. Book (and I) favor a defensive approach: Catch errors as soon as possible. Fail gracefully when something goes wrong. 16

Exceptions and Abstractions Sometimes have a choice: Requires specification, or check and throw exception? Two points of view: Defensive: Shorter Requires clauses are better. Check for bad conditions and throw exceptions. Passive-Aggressive : Too many exceptions make specifications confusing, too many checks make code confusing. Partial functions can be easier. Book (and I) favor a defensive approach: Catch errors as soon as possible. Fail gracefully when something goes wrong. 17

Local vs. Non-Local Use Public methods need to be as robust as possible. Never trust your caller to call you right. Behave responsibly even if caller does not. Not such a big deal in private methods. All possible call sites are in same file! But still a good idea to check inputs before risky operations. Use Java s assert statement. E.g.: assert s!= null : String argument is null. ; By default, assertions disabled, so does nothing. If run with assertions enabled, Evaluates s!= null. If false, throws AssertionError( String ) Never assert anything you think could possibly fail. Don t try to catch AssertionError. Don t document that you throw it. Assertions should be covered by Requires clause. 18

Assertion Demo

Propagate or Handle? If your procedure calls another that raises an exception, three choices: Don t catch; let it escape (add to your throws clause if checked). Catch it and throw something else ( exception translation ). Your spec says throws IllegalArgumentException if string is not in table. Table lookup method throws NotFoundException. try { lookup(s); } catch (NotFoundException nfe) { throw new IllegalArgumentException(s).initCause(nfe); } Include caught exception as cause of thrown exception. Catch it, solve problem, caller never knows. Book calls first two reflecting and last masking. 20

Something the Book Doesn t t Say It s OK to use Java s built-in exception types if they make sense. /** Searches for a string in an array. * @param a an array of strings * @param s a string * @throws java.lang.nullpointerexception if a == null or s == null. * */ Can avoid explicit null checks this way: Just try to use the object, and the right thing will happen. Other useful predefined exception types (all unchecked): java.lang.indexoutofboundsexception java.lang.illegalargumentexception (very useful!) java.lang.illegalstateexception ( you can t do that now. ) 21

Failure Atomicity Don t forget: Exceptions you throw may be caught! Throw exception give up and quit. Caller may try again, or move on to something else. That s the whole point! If you must throw an exception, leave things in consistent state. Try to test for bad cases before any side effects. Clean up after yourself (close open files, etc.). More on consistent state in Chapter 4. 22

Uncaught Exceptions What happens when an exception is thrown and not caught? Entire program crashes, with stack trace. (Even if there s more than one thread.) Confusing twist: Event handlers in Swing programs. Framework catches exception, prints stack trace, program keeps going. 23

Uncaught Exceptions What happens when an exception is thrown and not caught? Entire program crashes, with stack trace. (Even if there s more than one thread.) Confusing twist: Event handlers in GUI programs. Framework catches exception, prints stack trace, program keeps going. 24

New Rule Code you write for CS 3 should never crash with an uncaught exception. (Or elicit those messages from the AWT event thread.) Think of everything that might go wrong; Have a plan for every case! At the very least, inform user of problem in a civilized way before calling System.exit(1). 25