David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Yoshi
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 16: Concurrent Programming.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
1 CS2200 Software Development Lectures 28: Exception Handling A. O’Riordan, 2008 (Includes some slides by Lewis/Loftus 2005 and K. Brown )
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Class 14: Object-Oriented Programming Fall 2010 University of Virginia David Evans cs2220: Engineering Software.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions and assertions CSE 331 University of Washington.
Cs2220: Engineering Software Class 6: Defensive Programming Fall 2010 University of Virginia David Evans.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 12: Subtyping Rules What’s the.
Cs205: engineering software university of virginia fall 2006 Subtyping and Inheritance David Evans Quiz Friday: classes through.
1 Features of Java (2) CS 3331 Sections 4.5 and 4.6.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 9: Designing Exceptionally.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Cs205: engineering software university of virginia fall 2006 Programming Exceptionally David Evans
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Java Programming Language
Introduction to Exceptions in Java
CS102 – Exceptions David Davenport Latest: May 2015
Testing and Exceptions
Advanced Programming Behnam Hatami Fall 2017.
ATS Application Programming: Java Programming
Abdulmotaleb El Saddik University of Ottawa
Lecture 9: Exceptions in Java CS201j: Engineering Software
Lecture 5: Code Red, Ariane 5, and Gambling
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Lecture 4: Data Abstraction CS201j: Engineering Software
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
Lecture 13: Subtyping Rules Killer Bear Climber
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally

2 October 2003CS 201J Fall Last Time… No checking –Assume programmers know what they are doing Run-time checking –Check for anomalous behavior during program execution Static checking –Check at compile-time –Know properties of all possible executions before executing code

2 October 2003CS 201J Fall Exceptions in Java

2 October 2003CS 201J Fall StringSet choose public class StringSet { Vector els; // a Vector of String objects els != null els.elementType == \type(String) els.containsNull == false … public String choose () // EFFECTS: Returns an element of this. { return (String) els.firstElement (); }

2 October 2003CS 201J Fall What can go wrong… > java TestClient Exception in thread "main" java.util.NoSuchElementException at java.util.Vector.firstElement(Vector.java:450) at StringSet.choose(StringSet.java:54) at TestClient.test(TestClient.java:22) at TestClient.main(TestClient.java:4) public static void test () { StringSet s = new StringSet (); s.insert ("Alpha"); s.remove (s.choose ()); }

2 October 2003CS 201J Fall public class StringSet { Vector els; // a Vector of String objects els != null els.elementType == \type(String) els.containsNull == false … public String choose () // REQUIRES: this has at least one element // EFFECTS: Returns an element of this. { return (String) els.firstElement (); }

2 October 2003CS 201J Fall Use Exceptions to Remove Requires public String choose () throws EmptyException // EFFECTS: If this has at least one // element, returns an element of this. // Otherwise, throws EmptyException.

2 October 2003CS 201J Fall Throwing Exceptions public String choose () throws EmptyException // EFFECTS: If this has at least one element, returns an // element of this. Otherwise, throws EmptyException. { if (size () == 0) throw new EmptyException (); return (String) els.firstElement (); } What is EmptyException?

2 October 2003CS 201J Fall Exceptions are Objects public class EmptyException extends Exception { public EmptyException () { super (); } extends Exception means EmptyException inherits from the Exception type (in the Java API). Exception EmptyException We will cover subtyping and inheritance next week.

2 October 2003CS 201J Fall Catching Exceptions public class SetClient { public static void test () { StringSet s = new StringSet (); s.insert ("Alpha"); try { s.remove (s.choose ()); } catch (EmptyException e) { System.err.println ("Got EmptyException!"); System.exit (1); } System.out.println (“Done”); } Code inside the try block executes normally until it throws an exception. If no exception is thrown, execution proceeds after the catch. If the EmptyException exception is thrown, the catch handler runs.

2 October 2003CS 201J Fall Propagating Exceptions public class SetClient { public static void main (String []args) { StringSet s = new StringSet (); s.insert ("Alpha"); s.remove (s.choose ()); System.out.println (“Done”); } public class StringSet { public String choose () { return (String) els.firstElement (); } SetClient.main StringSet.choose Vector.firstElement calls NoSuchElementException throws looking for catch handler looking for catch handler looking for catch handler Exception in thread "main" java.util.NoSuchElementException at java.util.Vector.firstElement(Vector.java:450) at StringSet.choose(StringSet.java:54) at SetClient.main(SetClient.java:6)

2 October 2003CS 201J Fall Checked Exceptions Java has two types of exceptions: checked exceptions and run time exceptions Checked exceptions must be caught –Java compiler will not allow a program that could have an unchecked checked exception (so they don’t propagate to caller) Run time exceptions need not be caught –Subtype of RuntimeException –Propagate automatically up stack until caught

2 October 2003CS 201J Fall Catching Exceptions public class SetClient { public static void main (String args[]) { StringSet s = new StringSet (); s.insert ("Alpha"); System.out.println (s.choose ()); } > javac SetClient.java SetClient.java:5: unreported exception EmptyException; must be caught or declared to be thrown

2 October 2003CS 201J Fall Guidelines Use unchecked exceptions when the exception is not part of the client interface: –Specified precondition is violated –Defensive programming Assertion violated Use checked exceptions when: –An unusual situation prevents the implementation from satisfying the normal postcondition

2 October 2003CS 201J Fall Does Java API follow our guidelines? public final Object firstElement() // EFFECTS: If this vector has no elements, throws // NoSuchElementException. Otherwise, returns // the first component of this vector. public class StringSet { Vector els; // a Vector of String objects public String choose () // EFFECTS: Returns an element of this. { return (String) els.firstElement (); } NoSuchElementException is a Runtime Exception, so there is no compiler warning for choose.

2 October 2003CS 201J Fall Pop Quiz!

2 October 2003CS 201J Fall Specifying Exceptional Behavior Checked exceptions are part of the client interface: should be specified ESC/Java exsures annotation: N (ExceptionType) E If the procedure returns normally, the postcondition N is true. If the procedure throws an exception of type ExceptionType, E is true.

2 October 2003CS 201J Fall Specifying Choose public String choose () throws EmptyException \result != null (EmptyException) numEntries == 0 { if (size () == 0) throw new EmptyException (); return (String) els.firstElement (); }

2 October 2003CS 201J Fall Exceptions Considered Harmful Interfaces are more complicated – caller needs to worry about possible exceptions as well as result Makes it harder to understand programs –Control flow jumps around like a goto

2 October 2003CS 201J Fall PS2 AverageLength public class AverageLength { public static void main String args[]) throws RuntimeException { String filename = args[0]; try { FileInputStream infile = new FileInputStream (filename); StringTable names = new StringTable (infile); int numnames = names.size (); int totallength = 0; for (int index = 0; index <= numnames; index++) { String name = names.getNthLowest (index); totallength = totallength + name.length (); } System.out.println ("The average name length is: " + (double) totallength / numnames); } catch (FileNotFoundException e) { System.err.println ("Cannot find file: " + filename); System.exit (1); }

2 October 2003CS 201J Fall Exceptions Considered Helpful Provide a way to deal with abnormal conditions –Better than returning “special” values since caller may forget to check for them Allow you to deal with errors (e.g., file not found) up the call stack where more context information is available Separate normal code from error handling

2 October 2003CS 201J Fall Charge PS4 Design Documents due today In Section Friday, you will discuss your design with another team –Similarities and differences –What is better/worse about each design –What will make it more/less difficult to implement correctly