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

Size: px
Start display at page:

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

Transcription

1 CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions. 1 TWO USES FOR EXCEPTIONS Two broad situations where we use exceptions to report and react to: failures, typically producing erroneous or meaningless results. special cases, distinct from default cases but returning meaningful results. Although the distinction between the two is not always sharp, it is important to keep them separate and note their differences. Failures leading to erroneous results often require, but not always, program termination. These are errors which the program cannot recover from or which may undermine the integrity of other parts in the software installation. Special cases never require program termination. They correspond to boundary or limit conditions that are entirely expected by the programmer and require special handling separate from the common handling of the majority of default cases before allowing the program execution to continue and terminate gracefully. 2

2 TWO KINDS OF EXCEPTIONS The two uses of exceptions above roughly correspond to two different kinds: unchecked exceptions, typically used to report failures or serious errors likely leading to meaningless results. Use these exceptions for abnormal situations which it is hard to know where they come from. checked exceptions, typically used to report special cases or errors from which the program can recover gracefully. General guideline: Use unchecked exceptions for programming errors, from which recovery is impossible and continued execution will likely do more harm than good. Use checked exceptions for conditions from which the caller can reasonably be expected to recover. 3 TWO WAYS OF WRITING EXCEPTIONS Exceptions can be obtained in two different ways: library exceptions, many already written and tested in widespread practice, available for copying from the Java API. user-defined exceptions, written by the software developer according to need. General guideline: Favor the use of standard library exceptions. 4

3 Recommended Preferences: (1) checked over unchecked (2) subtype over supertype (3) library over user-defined (1) is debatable, (2) and (3) are not. 5 EXAMPLE: Three Specifications for the Factorial Function 1. An input x 0 is an error: public static int factorial (int x) // REQUIRES: x > 0 // EFFECTS: returns x! 2. An input x 0 returns a special value (not the factorial of a number): public static int factorial (int x) // EFFECTS: if x > 0 then returns x! else returns 0 3. An input x 0 throws an exception: public static int factorial (int x) // EFFECTS: if x > 0 then returns x! else returns an exception Question: Compare the three specifications. Which is to be preferred? 6

4 EXAMPLE: Three Implementations for the Factorial Function 1. On input x 0, there is no obligation to return anything: public static int factorial (int x) { // REQUIRES: x > 0 // EFFECTS: returns x! int fact = 1; while (x > 1) { fact = fact * x; x = x - 1; ; return fact; 2. On input x 0, the special value 0 is returned: public static int factorial (int x) { // EFFECTS: if x > 0 then returns x! else returns 0 if (x < 0) return 0; int fact = 1; while (x > 1) { fact = fact * x; x = x - 1; ; return fact; 7 3a. On input x 0, a library unchecked extension is thrown: public static int factorial (int x) { // EFFECTS: if x > 0 then returns x! else returns an exception if (x < 0) throw new IllegalArgumentException( x must be >= 0 ); int fact = 1; while (x > 1) { fact = fact * x; x = x - 1; ; return fact; 3b. On input x 0, a user-defined checked exception is thrown: public static int factorial (int x) throws NonPositiveException { /* a checked exception must be declared */ // EFFECTS: if x > 0 then returns x! else returns an exception if (x < 0) throw new NonPositiveException( x must be >= 0 ); int fact = 1; while (x > 1) { fact = fact * x; x = x - 1; ; return fact; While the unchecked exception in (3a) is optionally handled, the checked exception in (3b) must be handled. For handling of exceptions, see Sections and in [PDJ]. 8

5 EXAMPLE: Mixing Specifications and Exceptions Specification 3 on page 6 includes an exception, without naming one. We may need to be more specific and name the exceptions we want, as in the following postcondition: // EFFECTS: // if (array == null) // throws NullPointerException // else if (there is no i such that elem.equals(array[i])) // throws NoSuchElementException // else // return an i such that elem.equals(array[i]) 9 LIBRARY EXCEPTIONS FOR FAILURES AND SPECIAL CASES For Unrecoverable Failures (with unchecked exceptions) the VM has run out of memory (use OutOfMemoryError < VirtualMachineError < Error) a class file is corrupted and cannot be read (use ClassFormatError < LinkageError < Error) For Recoverable Failures? (with unchecked exceptions) the program has tried to read past the end of an array (use ArrayIndexOutOfBoundsException < IndexOutOfBoundsException < RuntimeException) For Recoverable Failures? Or Special Cases? (with checked exceptions) the end of a file is reached (use EOFException < IOException < Exception) a class file is missing (use ClassNotFoundException < Exception) 10

6 DISTINCTION BETWEEN FAILURE AND SPECIAL CASE The distinction is not always sharp and may depend on the context. Example: Is division by zero a failure or a special case? It depends. In a real-time navigational system that calls a procedure to compute the rate of descent, by dividing altitude by time elapsed, division by zero may be the result of an error with catastrophic consequences. This is a failure. Computing the average grade in a course where all the students are auditors, and none is registered for credit, division by zero is without grave consequences. The program should continue to compute other statistics about the course without problem. This is a special case. 11 EXERCISE: What kind of exception do you recommend to use in each of the following. Describe a situation that justifies your choice. 1. Someone tries to set the capacity of an object PassengerVehicle to a negative value. 2. A syntax error is found in a configuration file that an object uses to set its initial state. 3. A method that searches for a programmer-specified word in a string array cannot find any occurrence of the word. 4. A file provided to a method as input does not exit. 5. A file provided to a method as input exists, but security prevents the user from using it. 6. During an attempt to open a network connection to a remote server process, the remote machine cannot be contacted. 7. In the middle of a conversation with a remote server process, the network connection stops operating. 12

7 USER-DEFINED EXCEPTIONS FOR SPECIAL CASES Mostly Checked A common approach to handling special cases is to return special values. For example, lookup operations in the Java library are often designed so that the special value -1 is returned when expecting a positive integer, or the special reference null when expecting an object (a non-null reference). However, it becomes tedious to check the returned value every time, and it is easy to forget to do it. And sometimes it is not easy to think of a meaningful special value. 13 Example: User-Defined Checked Exception for a Special Case Suppose we have a class BirthdayBook with a lookup method with heading: Date lookup (String name) {... If the birthday book does not have an entry for the person whose name is given to the method lookup, we may decide to return a special value that cannot be a real date, e.g., 12/31/99. A cleaner approach is to throw a (user-defined checked) exception named NotFoundException which extends the library Exception : Date lookup (String name) throws NotFoundException {... if... // test for not found throw new NotFoundException ();... In this approach, the caller handles the exception with a catch clause, with no need for a special value or for the checking associated with it. 14

8 Example: User-Defined Checked Exception for a Special Case You are a bike dealer and need to validate a customer s order. Define a new class TooManyException that is a subclass of Exception, and if someone tries to order more bikes than you can ship, throw this checked exception: public class TooManyException extends Exception { public TooManyException () { super(); public TooManyException (String msg) { super(msg); public class BikeOrder { static void validateorder(string bikemodel,int quantity) throws TooManyException {... // perform some data validation, and if you do not like // the quantity for the specified model, do the following: throw new TooManyException ("Can not ship" + quantity + " bikes of the model " + bikemodel +); public class Order { try { BikeOrder.validateOrder ("Model-123", 50); // the next line will be skipped in case of an exception System.out.println ("The order is valid"); catch (TooManyException e) { txtresult.settext(e.getmessage()); 15 Example: User-Defined Unchecked Exception for a Special Case From [JC], page 244: /** A ChessMoveException is thrown when the user makes an illegal move */ public class ChessMoveException extends RuntimeException { public ChessMoveException () { super (); public ChessMoveException (String msg) { super(msg); Following custom, whenever subclassing the library RuntimeException or Exception in order to introduce a user-defined exception, at least one constructor without argument and one constructor with a single string argument are provided. 16

9 Example: Misusing Exceptions What does the following code do? (from [EJ] page 169) try { int i = 0; while (true) a[i++].f() ; catch (ArrayIndexOutofBoundsException e) { The infinite loop terminates by throwing, catching and ignoring an ArrayIndexOutofBoundsException when it attempts to access the first array element outside the bounds of the array. It is supposed to be equivalent to: for (int i = 0; i < a.length; i++) a[i].f(); 17 The exception-based idiom is a misguided attempt to improve performance based on the faulty reasoning that, since the VM checks the bounds of array accesses, the normal loop termination test (i < a.length) is redundant and should be avoided. However, because exceptions are designed for use only in exceptional circumstances, VM implementations rarely attempt to optimize their performance. On a typical machine, the exception-based idiom runs 70 times slower than the standard idiom when looping from 0 to 99. Moreover, the exception-based idiom is not guaranteed to work. Suppose the computation of f() in the body of the loop contains a bug that results in raising an ArrayIndexOutofBoundsException because of some unrelated array. If the standard idiom is used, the bug will generate an uncaught exception, resulting in immediate thread termination with an appropriate error message. If the exception-based idiom is used, the bug-related exception will be caught and misinterpreted as a normal loop termination. 18

10 REPLACING/ENFORCING PRECONDITIONS WITH EXCEPTIONS? A design issue is whether to use a precondition (in a method specification), and if so, whether to verify that it holds. Including a precondition in a method specification does not mean it has to be verified. On the contrary, preconditions are often used precisely because it would be too difficult to verify the property they define. Nonetheless, method callers do not like preconditions, which put the burden on them to make sure they do not call the method in a state violating the precondition. Hence, as a convenience to users, library methods tend to omit preconditions and, instead, throw exceptions when arguments are inappropriate. Sometimes this is not possible or recommended, i.e., it is better to keep a precondition and not replace it or to keep it without enforcing it with an exception. For example, in the Java standard library, the binary-search method of the Array class require that the array be sorted. But to verify that the array is indeed sorted takes linear time which is costlier than the logarithmic time of binary search! In this case, it is pointless to verify whether the array is sorted and, if it is not, to raise an exception; it simpler and more efficient to keep the precondition requiring the array be sorted. 19 Question: Should exceptions that are introduced to replace/enforce preconditions be checked exceptions or unchecked exceptions? If you have a precondition and you wish to replace (or enforce) it with an exception, it is preferable to throw an unchecked exception, rather than a checked exception. This is justified on the ground that callers cannot be expected to handle the exception, as they do not know enough to set up the method call properly in the first place. 20

11 CHECKED OR UNCHECKED EXCEPTIONS? The guideline proposed earlier in this handout was: If there is a choice, choose checked exceptions for special cases and unchecked exceptions for failures. But this is still too crude a guideline. Consider the design of a queue abstraction. Suppose you want your design to keep popping the queue until an exception is thrown. This is a special case, and so you choose a checked exception, which also requires that every call to the queue must be wrapped in a try-catch statement. Suppose some client wants to use the queue in a context in which, immediately prior to popping, the client tests whether the queue is empty and only pops if it is not. Nevertheless, this client still needs to wastefully wrap the call in a try-catch statement. Such a client would prefer an unchecked exception. 21 A more refined guideline is proposed in Sidebar 4.2, page 73, in [PDJ]: You should use an unchecked exception only if you expect that users will usually write code that ensures the exception will not happen, because there is a convenient and inexpensive way to avoid the exception, the context of use is local. Otherwise, you should use a checked exception. DEFENSIVE PROGRAMMING, EXCEPTIONS AND ASSERTIONS Look up appropriate pages in the index of [PDJ]. Also read pages in [JN]. 22

Assertions and Exceptions Lecture 11 Fall 2005

Assertions and Exceptions Lecture 11 Fall 2005 Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,

More information

Chapter 13 Exception Handling

Chapter 13 Exception Handling Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions 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

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (IS120) Lecture 30 April 4, 2016 Exceptions hapter 27 HW7: PennPals hat Due: Tuesday Announcements Simplified Example class { public void foo() {.bar(); "here in foo");

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

EXCEPTION HANDLING. Summer 2018

EXCEPTION HANDLING. Summer 2018 EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment

More information

CS112 Lecture: Exceptions and Assertions

CS112 Lecture: Exceptions and Assertions Objectives: CS112 Lecture: Exceptions and Assertions 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions 3. Introduce assertions Materials: 1. Online Java documentation

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018 Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 Exceptions and Assertions 1 Outline General concepts about dealing with errors and failures Assertions: what, why, how For things you believe

More information

2IP15 Programming Methods

2IP15 Programming Methods Lecture 3: Robustness 2IP15 Programming Methods From Small to Large Programs Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology

More information

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

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 })); A student adds a JUnit test: To Think About @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems

More information

Data Structures. 02 Exception Handling

Data Structures. 02 Exception Handling David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

CS61B Lecture #12. Today: Various odds and ends in support of abstraction. CS61B Lecture #12 Today: Various odds and ends in support of abstraction. Readings: At this point, we have looked at Chapters 1 9 of Head First Java. Today s lecture is about Chapters 9 and 11. For Friday,

More information

Exceptions. CSC207 Winter 2017

Exceptions. CSC207 Winter 2017 Exceptions CSC207 Winter 2017 What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment:

More information

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

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

More information

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

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 })); A student adds a JUnit test: Recreation @Test public void mogrifytest() { assertequals("mogrify fails", new int[] { 2, 4, 8, 12 }, MyClass.mogrify(new int[] { 1, 2, 4, 6 })); } The test always seems to

More information

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 19 Programming Exceptions CSE11 Fall 2013 Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:

More information

Exceptions and assertions

Exceptions and assertions Exceptions and assertions CSE 331 University of Washington Michael Ernst Failure causes Partial failure is inevitable Goal: prevent complete failure Structure your code to be reliable and understandable

More information

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

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions CS112 Lecture: Exceptions Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions Materials: 1. Online Java documentation to project 2. ExceptionDemo.java to

More information

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

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

More information

Chapter 12 Exception Handling

Chapter 12 Exception Handling Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can

More information

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

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed 1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

Software Construction

Software Construction Lecture 5: Robustness, Exceptions Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering & Technology

More information

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

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

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

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

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions 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

More information

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

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

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Exception in thread main java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling. Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

Assertions, pre/postconditions

Assertions, pre/postconditions Programming as a contract Assertions, pre/postconditions Assertions: Section 4.2 in Savitch (p. 239) Specifying what each method does q Specify it in a comment before method's header Precondition q What

More information

Designing Robust Classes

Designing Robust Classes Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations

More information

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

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

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

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Exception Handling. Chapter 9

Exception Handling. Chapter 9 Exception Handling Chapter 9 Objectives Describe the notion of exception handling React correctly when certain exceptions occur Use Java's exception-handling facilities effectively in classes and programs

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

Internal Classes and Exceptions

Internal Classes and Exceptions Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

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

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what

More information

COMP1008 Exceptions. Runtime Error

COMP1008 Exceptions. Runtime Error Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server

More information

Exception Handling Advanced Programming Techniques

Exception Handling Advanced Programming Techniques Exception Handling Advanced Programming Techniques https://no.wikipedia.org/wiki/tastatur#/media/file:computer_keyboard.png Prof. Dr. Bernhard Humm FB Informatik, Hochschule Darmstadt 1 Agenda Motivation

More information

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES 1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser

More information

Exceptions in Java

Exceptions in Java Exceptions in Java 3-10-2005 Opening Discussion Do you have any questions about the quiz? What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment?

More information

17. Handling Runtime Problems

17. Handling Runtime Problems Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems

More information

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

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what

More information

Lecture 10 Assertions & Exceptions

Lecture 10 Assertions & Exceptions CSE 331 Software Design and Implementation OUTLINE Lecture 10 Assertions & Exceptions Zach Tatlock / Winter 2016 Exceptions: what, how in Java How to throw, catch, and declare exceptions Failure happens!

More information

L3: Specifications. Introduction. Why Specifications? Today o Preconditions & postconditions o Exceptions Required reading (from the Java Tutorial)

L3: Specifications. Introduction. Why Specifications? Today o Preconditions & postconditions o Exceptions Required reading (from the Java Tutorial) 6.005 Software Construction Fall 2011 Prof. Rob Miller Today o Preconditions & postconditions o Exceptions Required reading (from the Java Tutorial) Exceptions Packages Controlling Access Introduction

More information

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology Exceptions Algorithms Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Exceptions ± Definition

More information

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

CSE 331 Software Design and Implementation. Lecture 12 Assertions & Exceptions CSE 331 Software Design and Implementation Lecture 12 Assertions & Exceptions Zach Tatlock / Spring 2018 OUTLINE General concepts about dealing with errors and failures Assertions: what, why, how For things

More information

Lecture 12 Assertions & Exceptions

Lecture 12 Assertions & Exceptions CSE 331 Software Design and Implementation Lecture 12 Assertions & Exceptions Zach Tatlock / Spring 2018 Exceptions: what, how in Java How to throw, catch, and declare exceptions Failure happens! Failure

More information

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

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

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the maximum, or Integer. MIN_VALUE 3 * if the array has length 0. 4 ***************************************************

More information

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions Chapter 15 Exception Handling Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn

More information

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO rights reserved. 2 Motivation When a program runs into a runtime error, the program terminates

More information

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

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Intro to Computer Science II. Exceptions

Intro to Computer Science II. Exceptions Intro to Computer Science II Exceptions Admin Exam review Break from Quizzes lab questions? JScrollPane JScrollPane Another swing class Allows a scrollable large component. JList? Constructors See next

More information

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance

More information

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

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations. CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations. 1 RUNTIME ERRORS All of us have experienced syntax errors. This

More information

14. Exception Handling

14. Exception Handling 14. Exception Handling 14.1 Intro to Exception Handling In a language without exception handling When an exception occurs, control goes to the operating system, where a message is displayed and the program

More information

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

Introduction to Java. Handout-3a. cs402 - Spring Introduction to Java Handout-3a cs402 - Spring 2003 1 Exceptions The purpose of exceptions How to cause an exception (implicitely or explicitly) How to handle ( catch ) an exception within the method where

More information

Correctness and Robustness

Correctness and Robustness Correctness and Robustness 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Introduction

More information

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1 References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1 Assertions Statements about input to a routine or state of a class Have two primary roles As documentation,

More information

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

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

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down CS112-2012S-22 Exceptions 1 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected situation Logic error in code Like to handle these errors gracefully, not just halt the program

More information

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. CS61B Lecture #12 Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. Lateness: Yes, the lateness policy does extend to Project 0. Test 1: still scheduled for 16

More information

Exceptions - Example. Exceptions - Example

Exceptions - Example. Exceptions - Example - Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

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

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors Preconditions Functions often have requirements on their inputs // Return maximum element in A[i..j] int findmax(int[] A, int i, int j) {... A is nonempty Aisn't null iand j must be nonnegative iand j

More information

CSE 143 Java. Exceptions 1/25/

CSE 143 Java. Exceptions 1/25/ CSE 143 Java Exceptions 1/25/17 12-1 Verifying Validity of Input Parameters A non-private method should always perform parameter validation as its caller is out of scope of its implementation http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 25 Nov. 8, 2010 ExcepEons and the Java Abstract Stack Machine Announcements Homework 8 (SpellChecker) is due Nov 15th. Midterm 2 is this Friday, November

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

Exceptions and Error Handling

Exceptions and Error Handling Exceptions and Error Handling Michael Brockway January 16, 2015 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent

More information

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

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

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

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract Specification and validation [L&G Ch. 9] Design patterns are a useful way to describe program structure. They provide a guide as to how a program fits together. Another dimension is the responsibilities

More information

Lecture 4: Procedure Specifications

Lecture 4: Procedure Specifications Lecture 4: Procedure Specifications 4.1. Introduction In this lecture, we ll look at the role played by specifications of methods. Specifications are the linchpin of team work. It s impossible to delegate

More information

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

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

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

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

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

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

More information

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

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others COMP-202 Exceptions Lecture Outline Exceptions Exception Handling The try-catch statement The try-catch-finally statement Exception propagation Checked Exceptions 2 Exceptions An exception is an object

More information

Motivations. Chapter 12 Exceptions and File Input/Output

Motivations. Chapter 12 Exceptions and File Input/Output Chapter 12 Exceptions and File Input/Output CS1: Java Programming Colorado State University Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the

More information

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

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and

More information