Programming Languages and Techniques (CIS120e)

Similar documents
Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

G Programming Languages - Fall 2012

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

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

Programming Languages and Techniques (CIS120)

G((#+(0,&,(;-) !"#$"%&&'($)*%($+%$,-)) %(.)/,01('2+,-) ,:) BC0,DE#(-) BC0,DE#(-) *,0;+",)8<) BC0,DE#(-)%(.);1,)F%>%)GH-;"%0;)6;%0I)J%01'(,)

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

Programming Languages and Techniques (CIS120)

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

CS159. Nathan Sprague

Java Programming Unit 7. Error Handling. Excep8ons.

CSE 331 Software Design & Implementation

CS 3 Introduction to Software Engineering. 3: Exceptions

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

Programming Languages and Techniques (CIS120)

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

COMP1008 Exceptions. Runtime Error

ECE 122. Engineering Problem Solving with Java

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception-Handling Overview

Programming Languages and Techniques (CIS120)

Assertions and Exceptions Lecture 11 Fall 2005

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

BBM 102 Introduction to Programming II Spring Exceptions

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

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

Java Exceptions Version June 2009

CS193j, Stanford Handout #25. Exceptions

Exceptions - Example. Exceptions - Example

Object Oriented Programming

Exceptions in Java

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

BBM 102 Introduction to Programming II Spring 2017

Programming Languages and Techniques (CIS120)

Exceptions and assertions

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

Defensive Programming

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

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

CSE 143 Java. Exceptions 1/25/

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

Exceptions and Design

EXCEPTION HANDLING. Summer 2018

Introduction to Computer Science II CS S-22 Exceptions

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

Programming Languages and Techniques (CIS120)

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

Exceptions. CSC207 Winter 2017

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

14. Exception Handling

Chapter 13 Exception Handling

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

Object Oriented Programming

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

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

ITI Introduction to Computing II

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

Introductory Programming Exceptions and I/O: sections

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

What can go wrong in a Java program while running?

Software Construction

CS159. Nathan Sprague

Lecture 19 Programming Exceptions CSE11 Fall 2013

Programming II (CS300)

ITI Introduction to Computing II

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

Sri Vidya College of Engineering & Technology Question Bank

Program Correctness and Efficiency. Chapter 2

Error Management in Compilers and Run-time Systems

Java Loose Ends. 11 December 2017 OSU CSE 1

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

CS 11 java track: lecture 3

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017

Defensive Programming. Ric Glassey

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

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

CPSC 427: Object-Oriented Programming

2IP15 Programming Methods

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

COE318 Lecture Notes Week 10 (Nov 7, 2011)

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

COMP-202 Unit 9: Exceptions

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

6.Introducing Classes 9. Exceptions

Java: exceptions and genericity

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

Programming Languages and Techniques (CIS120)

Object Oriented Programming. Week 7 Part 1 Exceptions

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

Transcription:

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 12 th CIS120e / Fall 2010 2

ExcepEons Dealing with failure. CIS120e / Fall 2010 3

ExcepEons An excepeon is an object represeneng abnormal condieons. Its internal state describes what went wrong. Examples: NullPointPointerExcepEon, IllegalArgumentExcepEon, IOExcepEon Throwing an excepeon is an emergency exit from the current method. The excepeon propagates up the invocaeon stack unel it either reaches the top and the stack, in which case the program aborts with the error, or the excepeon is caught. Catching an excepeon lets callers take appropriate aceons to handle the abnormal circumstances. CIS120e / Fall 2010 4

Example class C {!!public void foo() {!!!bar();!!!system.out.println(!}!!public void bar() {!!!baz();!!!system.out.println( here in bar );!!}!!public void baz() {!!!throw new Exception();!!!System.out.println( here in baz );!!}! }! What happens if we do (new C()).foo();? CIS120e / Fall 2010 5

Workspace (new C()).foo();! Stack Heap CIS120e / Fall 2010 6

Workspace (new C()).foo();! Stack Heap CIS120e / Fall 2010 7

Workspace ().foo();! Stack Heap Allocate a new instance of C in the heap. CIS120e / Fall 2010 8

Workspace ().foo();! Stack Heap CIS120e / Fall 2010 9

Workspace bar();! Stack Heap Save a copy of the current workspace in the stack, leaving a hole, wricen _, where we return to. Push the this* pointer, followed by arguments (in this case none) onto the stack. *We ll explain the this pointer in more detail later. Suffice it to say that it s how we can find which code to run when an instance method like bar is invoked. CIS120e / Fall 2010 10

Workspace bar();! Stack Heap CIS120e / Fall 2010 11

Workspace baz();! here in bar );! Stack Heap CIS120e / Fall 2010 12

Workspace baz();! here in bar );! Stack Heap CIS120e / Fall 2010 13

Workspace throw new Exception();! here in baz );! Stack here in bar );! Heap CIS120e / Fall 2010 14

Workspace throw new Exception();! here in baz );! Stack here in bar );! Heap CIS120e / Fall 2010 15

Workspace throw ();! here in baz );! Stack here in bar );! Heap Exception! CIS120e / Fall 2010 16

Workspace throw ();! here in baz );! Discard the current workspace. Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. Stack here in bar );! Heap Exception! CIS120e / Fall 2010 17

Workspace Stack Heap Discard the current workspace. Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. here in bar );! Exception! CIS120e / Fall 2010 18

Workspace Stack Heap Discard the current workspace. Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. here in bar );! Try/Catch for ( )? Exception! No! CIS120e / Fall 2010 19

Workspace Stack Heap Discard the current workspace. Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. Try/Catch for ( )? Exception! No! CIS120e / Fall 2010 20

Workspace Stack Heap Try/Catch for ( )? No! Discard the current workspace. Exception! Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. CIS120e / Fall 2010 21

Workspace Stack Heap Program terminated with uncaught excepeon ( )! Discard the current workspace. Exception! Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. CIS120e / Fall 2010 22

Catching the ExcepEon class C {!!public void foo() {!!!bar();!!!system.out.println(!}!!public void bar() {!!!try {!!!!!!baz();!!!} catch (Exception e) { System.out.println( caught ); }!!!System.out.println( here in bar );!!}!!public void baz() {!!!throw new Exception();!!!System.out.println( here in baz );!!}! }! Now what happens if we do (new C()).foo();? CIS120e / Fall 2010 23

Workspace (new C()).foo();! Stack Heap CIS120e / Fall 2010 24

Workspace (new C()).foo();! Stack Heap CIS120e / Fall 2010 25

Workspace ().foo();! Stack Heap Allocate a new instance of C in the heap. CIS120e / Fall 2010 26

Workspace ().foo();! Stack Heap CIS120e / Fall 2010 27

Workspace bar();! Stack Heap Save a copy of the current workspace in the stack, leaving a hole, wricen _, where we return to. Push the this* pointer, followed by arguments (in this case none) onto the stack. *We ll explain the this pointer in more detail in the next lecture. Suffice it to say that it s how we can find which code to run when an object- local method like bar is invoked. CIS120e / Fall 2010 28

Workspace bar();! Stack Heap CIS120e / Fall 2010 29

Workspace try {! baz();! } catch (Exception e) { System.out.Println ( caught ); }! here in bar );! Stack Heap CIS120e / Fall 2010 30

Workspace try {! baz();! } catch (Exception e) { System.out.Println ( caught ); }! here in bar );! When execueng a try/catch block, push onto the stack a new workspace that contains all of the current workspace except for the try { } code. Stack Heap Replace the current workspace with the body of the try. CIS120e / Fall 2010 31

Workspace Stack Heap baz();! Body of the try. Everything else. When execueng a try/catch block, push onto the stack a new workspace that contains all of the current workspace except for the try { } code. Replace the current workspace with the body of the try. catch (Exception e) { System.out.Println ( caught ); }! here in bar );! CIS120e / Fall 2010 32

baz();! Workspace ConEnue execueng as normal. Stack catch (Exception e) { System.out.Println ( caught ); }! here in bar );! Heap CIS120e / Fall 2010 33

Workspace Stack Heap throw new Exception();! here in baz );! The top of the stack is off the bocom of the page catch (Exception e) { System.out.Println ( caught ); }! here in bar );! CIS120e / Fall 2010 34

Workspace Stack Heap throw new Exception();! here in baz );! catch (Exception e) { System.out.Println ( caught ); }! here in bar );! CIS120e / Fall 2010 35

Workspace Stack Heap throw ();! here in baz );! catch (Exception e) { System.out.Println ( caught ); }! here in bar );! Exception! CIS120e / Fall 2010 36

Workspace Stack Heap throw ();! here in baz );! Discard the current workspace. Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. catch (Exception e) { System.out.Println ( caught ); }! here in bar );! Exception! CIS120e / Fall 2010 37

Workspace Stack Heap Discard the current workspace. Then, pop saved workspace frames off the stack, looking for the most recently pushed one that contains a try/catch block whose catch clause declares a supertype of the excepeon being thrown. If no matching catch is found, abort the program with an error. catch (Exception e) { System.out.Println ( caught ); }! here in bar );! Try/Catch for ( )? Exception! No! CIS120e / Fall 2010 38

Workspace Stack Heap When a matching catch block is found, add a new binding to the stack for the excepeon variable declared in the catch. Then replace the workspace with catch body and the rest of the saved workspace. ConEnue execueng as usual. catch (Exception e) { System.out.Println ( caught ); }! here in bar );! Exception! Try/Catch for ( )? Yes! CIS120e / Fall 2010 39

Workspace Stack Heap { System.out.Println ( caught ); }! here in bar );! When a matching catch block is found, add a new binding to the stack for the excepeon variable declared in the catch. Then replace the workspace with catch body and the rest of the saved workspace. ConEnue execueng as usual. e! Exception! CIS120e / Fall 2010 40

Workspace Stack Heap { System.out.Println ( caught ); }! here in bar );! ConEnue execueng as usual. e! Exception! CIS120e / Fall 2010 41

Workspace Stack Heap { ; }! here in bar );! ConEnue execueng as usual. e! Exception! Console caught! CIS120e / Fall 2010 42

Workspace Stack Heap { ; }! here in bar );! We re sweeping a few details about lexical scoping of variables under the rug the scope of e is just the body of the catch, so when that is done, e must be popped from the stack. Console caught! e! Exception! CIS120e / Fall 2010 43

Workspace Stack Heap here in bar );! ConEnue execueng as usual. Exception! Console caught! CIS120e / Fall 2010 44

Workspace Stack Heap here in bar );! ConEnue execueng as usual. Exception! Console caught! CIS120e / Fall 2010 45

Workspace Stack Heap ;! Pop the stack when the workspace is done, returning to the saved workspace just aoer the _ mark. Exception! Console caught! here in bar! CIS120e / Fall 2010 46

Workspace Stack Heap ConEnue execueng as usual. Exception! Console caught! here in bar! CIS120e / Fall 2010 47

Workspace Stack Heap ConEnue execueng as usual. Exception! Console caught! here in bar! CIS120e / Fall 2010 48

Workspace Stack Heap ;! ConEnue execueng as usual. Exception! Console caught! here in bar! here in foo! CIS120e / Fall 2010 49

Workspace Stack Heap Program terminated normally. Exception! Console caught! here in bar! here in foo! CIS120e / Fall 2010 50

When No ExcepEon is Thrown If no excepeon is thrown while execueng the body of a try { } block, evaluaeon skips the corresponding catch block. i.e. if you ever reach a workspace where catch is the statement to run, just skip it: Workspace Workspace catch (Exception e) { System.out.Println ( caught ); }! here in bar );! here in bar );! CIS120e / Fall 2010 51

Catching ExcepEons There can be more than one catch clause associated with each try Matched in order, according to the dynamic type of the excepeon thrown. Helps refine the error handling try {! // do something with the IO library! } catch (FileNotFoundException e) {! // handle an absent file! } catch (IOException e) {! // handle other kinds of IO errors.! }! Good style: be as specific as possible about the excepeons you re handling. Avoid catch (Exception e) { } it s usually too generic! CIS120e / Fall 2010 52

ExcepEon Class Hierarchy Type of all throwable objects. Object Subtypes of ExcepEon must be declared. Throwable ExcepEon Error Fatal Errors, should never be caught. IOExcepEon RunEmeExcepEon IllegalArgumentExcepEon Subtypes of RunEmeExcepEon do not have to be declared. CIS120e / Fall 2010 53

Checked (Declared) ExcepEons ExcepEons that are subtypes of ExcepEon (but not RunEmeExcepEon) are called checked or declared. A method that might throw a checked excepeon must declare it using a throws clause in the method type. The method might raise a checked excepeon, either by: directly throwing such an excepeon public void maybedoit (String file) throws AnException {!!if ( ) throw new AnException(); // directly throw!! or, calling another method that might itself throw a checked excepeon public void dosomeio (String file) throws IOException {!!Reader r = new FileReader(file); // might throw!! CIS120e / Fall 2010 54

Unchecked (Undeclared) ExcepEons Subclasses of RunEmeExcepEon do not need to be declared via throws even if the method does not explicitly handle them. Many pervasive types of errors cause RunEmeExcepEons NullPointerExcepEon IndexOutOfBoundsExcepEon IllegalArgumentExcepEon public void mightfail (String file) {!!if (file.equals( dictionary.txt ) {!!!// file could be null!!!! The original intent was that such excepeons represent disastrous condieons from which it was impossible to sensibly recover CIS120e / Fall 2010 55

Declared vs. Undeclared? Tradeoffs in the sooware design process: Declared = becer documentaeon forces callers to acknowledge that the excepeon exists Undeclared = fewer staec guarantees but, much easier to refactor code In pracece: test- driven development encourages fail early/fail ooen model of code design and lots of code refactoring, so undeclared excepeons are prevalent. A good compromise? Declared excepeons for libraries, where the documentaeon and usage enforcement are criecal Undeclared for client- excepeons to facilitate more flexible code CIS120e / Fall 2010 56

Good Style for ExcepEons In Java, excepeons should be used to capture excep8onal circumstances Try/catch/throw incur performance costs and complicate reasoning about the program, don t use them when becer solueons exist Re- use exiseng excepeon types when they are meaningful to the situaeon e.g. use NoSuchElementExcepEon when implemeneng a container Define your own subclasses of ExcepEon when doing so can convey useful informaeon to possible callers that can handle the excepeon. It is ooen sensible to catch one excepeon and re- throw a different (more meaningful) kind of excepeon. e.g. when implemeneng WordScanner, we caught IOExcepEon and threw NoSuchElementExcepEon in the next() method. Catch excepeons as near to the source of failure as makes sense i.e. where you have the informaeon to deal with the excepeon Catch excepeons with as much precision as you can i.e. Don t do: try { } catch (ExcepEon e) { } instead do: try { } catch (IOExcepEon e) { } CIS120e / Fall 2010 57

Finally A finally clause of a try/catch/finally statement always gets run, regardless of whether there is no excepeon, a propagated excepeon, a caught excepeon, or even if the method returns from inside the try. Finally is most ooen used for releasing resources that might have been held/created by the try block: public void dosomeio (String file) {! FileReader r = null;! try {! r = new FileReader(file);! // do some IO! } catch (FileNotFoundException e) {! // handle the absent file! } catch (IOException e) {! // handle other IO problems! } finally {! if (r!= null) { // don t forget null check!! try { r.close(); } catch (IOException e) { }! }! }! }! 58

The Java Abstract Stack Machine 1. Class tables 2. Method invocaeons and this 3. StaEc members CIS120e / Fall 2010 59

Consider This Example public class Ctr {! private int x;! public Ctr () { x = 0; }! public void incby(int d) { x = x + d; }! public int get() { return x; }! }! public class Decr extends Ctr {! private int y;! public D (int inity) { y = inity; }! public void dec() { incby(-y); }! }! // somewhere in main:! Decr d = new Decr(2);! d.dec().get();! CIS120e / Fall 2010 60