CS61B L10 Exceptions (1)Garcia / Yelick Fall 2003 © UCB 2003-09-17  Dan Garcia (www.cs.berkeley.edu/~ddgarcia) Kathy Yelick  (www.cs.berkeley.edu/~yelick)

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Road Map Introduction to object oriented programming. Classes
11-Jun-15 Exceptions. 2 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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
16-Jun-15 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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
COMP Exception Handling Yi Hong June 10, 2015.
Low-Level Detailed Design SAD (Soft Arch Design) Mid-level Detailed Design Low-Level Detailed Design Design Finalization Design Document.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Exceptions and assertions CSE 331 University of Washington.
CS61B L12 Arrays and Implementing Enumerations (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
CS61B L11 Testing & Static (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS61B L07 Specification and Documentation (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
CS61B L06 Control Structures (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
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.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CS61B L13 Lists (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions in the Java programming language J. W. Rider.
Testing and Debugging.
Chapter 12 Exception Handling and Text IO
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Topics Introduction to File Input and Output
Chapter 12 Exception Handling
Effective Java, 3rd Edition Chapter 10: Exceptions
Web Design & Development Lecture 7
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Exception Handling Contents
Effective Java, Chapter 9: Exceptions
Exceptions 10-May-19.
Topics Introduction to File Input and Output
CMSC 202 Exceptions.
Presentation transcript:

CS61B L10 Exceptions (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  ( inst.eecs.berkeley.edu/~cs61b/ 1 Handout: notes Computer Science 61B Data Structures and Advanced Programming Lecture 10 – Exceptions

CS61B L10 Exceptions (2)Garcia / Yelick Fall 2003 © UCB Change which lines to protect invariant? 1: none 2: 2 3: 2&3 4: 2&4 5: 3&4 6: 2-4 7: 2-5 1)public class Landlord { 2) public Vector myPlots; 3) Landlord (Vector initP) { myPlots = initP; } 4) Vector getPlots () { return myPlots; } 5) Plot plotAt(int i) { return myPlots.get(i); } 6) } // invariant: Plots do not overlap

CS61B L10 Exceptions (3)Garcia / Yelick Fall 2003 © UCB Users’ variables Which Variables Are Problems? owner myPlots myStart mySize myStart mySize internalVec internalPlot internalVec is a problem, internalPlot is not … …

CS61B L10 Exceptions (4)Garcia / Yelick Fall 2003 © UCB Representation Exposure A well-designed data abstraction can guarantee its representation invariants –Variables are usually private to ensure invariants User may still be able to violate the invariants –Representation exposure: giving the user of an abstract data type access to the internals, allowing them to violate representation invariants If all fields are private, how does this happen? –Taking mutable objects from user and putting them into the internal state –Returning mutable parts of the state

CS61B L10 Exceptions (5)Garcia / Yelick Fall 2003 © UCB Abstraction Functions Given any legal concrete object, what is its abstract value? –A concrete object is the set of internal variables »The below-the-line view –The abstract value is in the programmer’s mind »The above-the-line view »e.g., a Fraction is a rational number, int1/int2 –A concrete object is legal if the representation invariant holds, I.e., repOk is true This object represents the rational number ½ : So does this one: 1 myNumer 2 myDenom 4 myNumer 8 myDenom 1212

CS61B L10 Exceptions (6)Garcia / Yelick Fall 2003 © UCB Abstraction Functions Abstraction functions map concrete to abstract values (below to above the line) –They are often many-to-one, because several concrete states may represent the same abstract object Liskov talks about abstraction functions as a documentation idea, but notation is difficult Instead, we will use the toString method as the abstraction function –The toString result is the abstract value The different implementations of Fraction have different toString methods: –If stored in lowest form, then toString is one-to-one –If not, toString is many-to-one

CS61B L10 Exceptions (7)Garcia / Yelick Fall 2003 © UCB What Makes a Good toString ? Design toString carefully; it should: 1.Distinguish between all distinct abstract values »If 2 objects are not.equals, their toString should not be 2.Not reveal internal information »If 2 objects are. equals, their toString should be Sometimes #1 is becomes too cumbersome: –A Landlord is shown: ---DD--KKK--D----- if Dan, Kathy, and David have all rented plots #2 means: don’t reveal redundant information –A linked list with a tail pointer or a size field –Information added to speed up operations

CS61B L10 Exceptions (8)Garcia / Yelick Fall 2003 © UCB Data Abstraction Summary Data Abstraction is a powerful programming tool –Hide the implementation details –Allow for future changes (better/faster…) Representation Invariant –Rules about how the internal variables are managed –repOk() checks whether rules have been violated Abstraction Function –Maps concrete representation to the abstract value –toString() typically defines this function Benevolent side effects –Modifications of internal state that are not externally visible

CS61B L10 Exceptions (9)Garcia / Yelick Fall 2003 © UCB What to do with Erroneous Input In mathematics, two kinds of functions: –Total function is one that is defined everywhere –Partial function is only defined on some values Same applied to programs –Methods are total if the spec has –Methods are partial if they do: behavior is not defined when must condition is not met Methods that are only partial are harder to use: –But what to do about “bad” input? »Creating a bank account with a negative balance »Reading from a file, which is suddenly deleted –Change the spec to define a particular behavior for every input, but was is the right behavior?

CS61B L10 Exceptions (10)Garcia / Yelick Fall 2003 © UCB Approaches to Handling Bad Inputs What to do about this (rare) kind of “exceptional” behavior? –Have every method take an extra parameter, which will be mutated if there is an exception –Have every method return a status, e.g., 0 for normal, nonzero if some exception occurred What about methods that already return values? public IslamicDate tomorrow() Return an object containing the normal value + status? Need to define a new class (Yuck!) Can we add an extra int argument for status? public IslamicDate tomorrow (int status) No: need to pass in a mutable status object (Yuck!)

CS61B L10 Exceptions (11)Garcia / Yelick Fall 2003 © UCB Java’s Approach to Exceptions Java allows you to write a method that either –Returns a normal value –Or returns a special “Exception” object A throw statement says to throw the Exception. if (input == null) { throw new IllegalArgumentException (“null input”); } Throwing an exception is like “return”: –The method exits  it should be inside a conditional or at the end of a method – nothing after it will run. –It will send back the given Exception object

CS61B L10 Exceptions (12)Garcia / Yelick Fall 2003 © UCB What are Exceptions? Exceptions are objects –Exceptions have methods, like getMessage() –The can be passed around and stored –They can be created using a constructor new Exception (“That was bad input”) –Are instance of Exception class, or some other class that is a subtype of Exception »Seen in the java API in the list at the top »More on this later They have special behavior: –Can throw and catch exceptions Object Exception... Integer

CS61B L10 Exceptions (13)Garcia / Yelick Fall 2003 © UCB When an Exception is Thrown Example of a Java method that doesn’t always work public static int readInt(BufferedReader br){ String input = br.readLine(); return Integer.parseInt(input); } Problem: readLine will fail sometimes if there are I/O problems, e.g., the file you are reading from is removed The specification for readLine says: public String readLine()throws IOException …stuff omitted Throws: IOException - If an I/O error occurs A method that calls readLine must handle the exception

CS61B L10 Exceptions (14)Garcia / Yelick Fall 2003 © UCB Handling Exceptions: Approach 1 Handle the exception in the caller public static int readInt(BufferedReader br) { try { String input = br.readLine(); return Integer.parseInt(input); } catch (IOException ioe) { System.err.println(“Unable to read int, ” + “defaulting to 0”); return 0; } No change to signature, but changes the internals Right approach if the problem can be fixed –The above example is dubious style, defaulting to 0

CS61B L10 Exceptions (15)Garcia / Yelick Fall 2003 © UCB Exception Handling in General General format for try/catch: try { Statements0 } catch (ExceptionName1 var1) { Statements1 } Statements2 Two possible executions: 1.Execute Statements0. If no exception occurs, skip catch and Statements1 and continue with Statement2 2.Start executing Statements0. If an exception occurs, stop in the middle of Statement0 (wherever you are), and jump to Statements1. Then go to Statements2. Declares name for exception object var1 can be used inside Statements1, e.g., var1.getMessage()

CS61B L10 Exceptions (16)Garcia / Yelick Fall 2003 © UCB Handling Exceptions: Approach 2 The second approach is to “pass the buck” Re-throw the exception from this method public static int readInt1(BufferedReader br) throws IOException { String input = br.readLine(); return Integer.parseInt(input); } This changes the signature and is the right approach if –The exception makes sense to callers of the method –Problem cannot be fixed within this method

CS61B L10 Exceptions (17)Garcia / Yelick Fall 2003 © UCB Throws vs. Throw A throws clause in a method signature says: 1.This method may throw the listed Exceptions 2.If any called procedures within throws them, they will be passed along public static int readInt1(BufferedReader br) throws IOException {... } A throw statement says to actually throw the throw new IOException(“No file”);

CS61B L10 Exceptions (18)Garcia / Yelick Fall 2003 © UCB Two Kinds of Exceptions All Exception types (named …Exception by convention) are subtypes of Exception 2 Kinds: “checked” exceptions “unchecked” exceptions Object Exception RuntimeException IllegalArgumentException NullPointerException IndexOutOfBoundsException (many others not shown) IOException (many others not shown) 1.Unchecked exceptions are subtypes of RuntimeException 2.Checked exceptions are everything else

CS61B L10 Exceptions (19)Garcia / Yelick Fall 2003 © UCB Exceptions When writing a method that throws an Exception: –Checked: Java requires throws in method signature –Unchecked (RuntimeException): Throws in method signature is allowed but not required When calling a method that throws an Exception: –Checked: Java requires either: »try/catch around method call »throws in method signature –Unchecked Exceptions do not require these. A “catch” clause with an exception type will catch any subtype, e.g, try {…} catch (Exception e) { } –This is very dangerous, why?

CS61B L10 Exceptions (20)Garcia / Yelick Fall 2003 © UCB PRS Question Given the Account class with the deposit method below, what will the the last line print? 1: 50 2: : Undef: behavior not specified 4: Compiler err 5: Runtime err public deposit (int amt) { int tmpBal = myBalance; myBalance -= amt; if (myBalance < 0) { throw new IllegalArgumentException(); myBalance = tmpBal; } // remaining code outside in main kathy = new Account(50); kathy.deposit(-1000); System.out.println(kathy.balance());

CS61B L10 Exceptions (21)Garcia / Yelick Fall 2003 © UCB Announcements - Quiz Open book/open notes Topics: –Basic Java 1.Writing and using classes and methods 2.Conditionals, loops, and recursion 3.Parameter passing 4.Primitive values vs. objects (and references to them) 5.public and private 6.static and non-static (hw3) 7.Using Exceptions (lab 4) 8.Vectors/Enumerations (lab 4) Note: repOK and loop invariants will not be on this modifies”) –Testing (lab 3, not specific test framework in next lecture)

CS61B L10 Exceptions (22)Garcia / Yelick Fall 2003 © UCB Announcements - Quiz Review session –Tuesday or Wednesday evening: watch newsgroup for details Exam questions often use examples you have seen. –We will include the code, but you will have time problems if you’re seeing it for the first time. Examples from labs and homeworks (through lab 4 and homework 3): –Account (lab) –Fraction (lecture) –StringFormat (hw) –StringCheck (lab) –IslamicDate (hw2) –Vector and Enumeration (lab) Solutions for labs and homeworks online