Programming Languages and Techniques (CIS120e)

Size: px
Start display at page:

Download "Programming Languages and Techniques (CIS120e)"

Transcription

1 Programming Languages and Techniques (CIS120e) Lecture 25 Nov. 8, 2010 ExcepEons and the Java Abstract Stack Machine

2 Announcements Homework 8 (SpellChecker) is due Nov 15th. Midterm 2 is this Friday, November 12 th CIS120e / Fall

3 ExcepEons Dealing with failure. CIS120e / Fall

4 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

5 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

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

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

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

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

10 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

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

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

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

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

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

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

17 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

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 );! Exception! CIS120e / Fall

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. here in bar );! Try/Catch for ( )? Exception! No! CIS120e / Fall

20 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

21 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

22 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

23 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

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

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

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

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

28 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

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

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

31 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

32 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

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

34 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

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

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

37 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

38 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

39 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

40 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

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

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

43 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

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

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

46 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

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

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

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

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

51 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

52 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

53 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

54 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

55 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

56 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

57 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

58 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

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

60 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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 March 25, 2013 ExcepDons Announcements HW 08 due tonight at midnight Weirich OH: 1:30 3PM today Midterm 2 is this Friday Towne 100 last names A

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 30 November 13, 2015 ExcepEons / IO Chapter 27 HW7: PennPals Chat Due: Tuesday, November 17 th Announcements Start today if you haven't already! Poll

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 29 April 7, 2014 ExcepEons Read Chapter 28 Announcements Homework 9 available later today, due Tuesday April 15 th at midnight Focus: working with

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (IS120) Lecture 30 April 6, 2015 ExcepEons hapter 27 Iterator quiz public static void iteratorexn() { List strs = new LinkedList(); strs.add(""); strs.add("is

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 30 April 4, 2018 I/O & Histogram Demo Chapters 28 HW7: Chat Server Announcements No penalty for late submission by tomorrow (which is a HARD deadline!)

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (IS120) Lecture 29 November 11, 2015 Overriding, Enums, ExcepFons HW07: PennPals is available Due Tuesday: November 17 th Start Early! Announcements Emphasizes: Java

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Week 13 - Part 2 Thomas Wies New York University Review Last lecture Scala Outline Today: Exceptions Sources for today s lecture: PLP, ch. 8.5 Exceptions

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int

More information

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

G((#+(0,&,(;-) !#$%&&'($)*%($+%$,-)) %(.)/,01('2+,-) ,:) BC0,DE#(-) BC0,DE#(-) *,0;+,)8<) BC0,DE#(-)%(.);1,)F%>%)GH-;%0;)6;%0I)J%01'(,) !"#$"%&&'($)*%($+%$,-)) %(.)/,01('2+,-) 3456789,:) G((#+(0,&,(;-) K#&,L#"I)@)36D,MM41,0I,":)'-).+,)=#>)7,&H,")78 ;1 )) *,0;+",)8?)@A)8979) BC0,DE#(-)%(.);1,)F%>%)

More information

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

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 Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 26, 2015 Inheritance and Dynamic Dispatch Chapter 24 public interface Displaceable { public int getx(); public int gety(); public void move

More information

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

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

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

Java Programming Unit 7. Error Handling. Excep8ons.

Java Programming Unit 7. Error Handling. Excep8ons. Java Programming Unit 7 Error Handling. Excep8ons. Run8me errors An excep8on is an run- 8me error that may stop the execu8on of your program. For example: - someone deleted a file that a program usually

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

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 25 March 18, 2013 Subtyping and Dynamic Dispatch Announcements HW07 due tonight at midnight Weirich OH cancelled today Help your TAs make the most

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

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

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

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 25 November 1, 2017 Inheritance and Dynamic Dispatch (Chapter 24) Announcements HW7: Chat Client Available Soon Due: Tuesday, November 14 th at 11:59pm

More information

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

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

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions. CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines

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

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

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

Java Exceptions Version June 2009

Java Exceptions Version June 2009 Java Exceptions Version June 2009 Motivation Report errors, by delegating error handling to higher levels Callee might not know how to recover from an error Caller of a method can handle error in a more

More information

CS193j, Stanford Handout #25. Exceptions

CS193j, Stanford Handout #25. Exceptions CS193j, Stanford Handout #25 Summer, 2003 Manu Kumar Exceptions Great Exceptations Here we'll cover the basic features and uses of exceptions. Pre-Exceptions A program has to encode two ideas -- how to

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

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.2) Exception Handling 1 Outline Throw Throws Finally 2 Throw we have only been catching exceptions that are thrown by the Java run-time system. However, it

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

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 31 November 17, 2017 I/O & Histogram Demo Chapters 28 Announcements HW8: SpellChecker Available on the website and Codio Due next Tuesday, November

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

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

Defensive Programming

Defensive Programming Defensive Programming Software Engineering CITS1220 Based on the Java1200 Lecture notes by Gordon Royle Lecture Outline Why program defensively? Encapsulation Access Restrictions Documentation Unchecked

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

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

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

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

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

Exceptions and Design

Exceptions and Design Exceptions and Exceptions and Table of contents 1 Error Handling Overview Exceptions RuntimeExceptions 2 Exceptions and Overview Exceptions RuntimeExceptions Exceptions Exceptions and Overview 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

Introduction to Computer Science II CS S-22 Exceptions

Introduction to Computer Science II CS S-22 Exceptions Introduction to Computer Science II CS112-2012S-22 Exceptions David Galles Department of Computer Science University of San Francisco 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected

More information

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

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 November 3, 2017 The Java ASM, Java Generics Chapter 24 Announcements HW7: Chat Server Available on Codio / InstrucNons on the web site Due Tuesday,

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

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

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

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

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

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

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

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

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

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

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

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

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

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course JAC444 - Lecture 4 Segment 1 - Exception 1 Objectives Upon completion of this lecture, you should be able to: Separate Error-Handling Code from Regular Code Use Exceptions to Handle Exceptional Events

More information

What can go wrong in a Java program while running?

What can go wrong in a Java program while running? Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage This lecture Summary on polymorphism, multiple

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

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

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

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

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

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2018 Lecture 11 EXCEPTION HANDLING Many higher-level languages provide exception handling Concept: One part of the program knows how to detect a problem,

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

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

Error Management in Compilers and Run-time Systems

Error Management in Compilers and Run-time Systems TDDB29 Compilers and Interpreters Error Management in Compilers and Run-time Systems Program errors major part of the total cost of software projects is due to testing and debugging. US-Study 2002: Software

More information

Java Loose Ends. 11 December 2017 OSU CSE 1

Java Loose Ends. 11 December 2017 OSU CSE 1 Java Loose Ends 11 December 2017 OSU CSE 1 What Else? A few Java issues introduced earlier deserve a more in-depth treatment: Try-Catch and Exceptions Members (static vs. instance) Nested interfaces and

More information

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

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis Principles of Software Construction: Objects, Design, and Concurrency Objects (continued) toad Spring 2012 Jonathan Aldrich Charlie Garrod School of Computer Science 2012 J Aldrich and W Scherlis Announcements

More information

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

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003 The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled

More information

CS 11 java track: lecture 3

CS 11 java track: lecture 3 CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces

More information

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017

Programming Language Concepts Scoping. Janyl Jumadinova January 31, 2017 Programming Language Concepts Scoping Janyl Jumadinova January 31, 2017 Scope Rules A scope is a program section of maximal size in which no bindings change, or at least in which no re-declarations are

More information

Defensive Programming. Ric Glassey

Defensive Programming. Ric Glassey Defensive Programming Ric Glassey glassey@kth.se Outline Defensive Programming Aim: Develop the programming skills to anticipate problems beyond control that may occur at runtime Responsibility Exception

More information

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11 CS24: INTRODUCTION TO COMPUTING SYSTEMS Spring 2015 Lecture 11 EXCEPTION HANDLING! Many higher-level languages provide exception handling! Concept: One part of the program knows how to detect a problem,

More information

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

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

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

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 19 November 7, 2018 CPSC 427, Lecture 19, November 7, 2018 1/18 Exceptions Thowing an Exception Catching an Exception CPSC 427, Lecture

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

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

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15 s Computer Science and Engineering College of Engineering The Ohio State University Lecture 15 Throwable Hierarchy extends implements Throwable Serializable Internal problems or resource exhaustion within

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

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

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

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

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

More information

Java: exceptions and genericity

Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exceptions Exceptions

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 29 Enums & Iterators Announcements Prof. Benjamin Pierce is lecturing today Will be teaching 120 again next Spring Enumerations Enumerations (a.k.a.

More information

Object Oriented Programming. Week 7 Part 1 Exceptions

Object Oriented Programming. Week 7 Part 1 Exceptions Object Oriented Programming Week 7 Part 1 Exceptions Lecture Overview of Exception How exceptions solve unexpected occurrences Catching exceptions Week 7 2 Exceptions Overview Week 7 3 Unexpected Occurances

More information

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

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1 CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship Java Review - Errors George Blankenship 1 Errors Exceptions Debugging Java Review Topics Java Review - Errors George Blankenship

More information