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

Size: px
Start display at page:

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

Transcription

1 Exceptions Revised 24-Jan-05 CMPUT 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 conditions. D. Szafron, C. Jones 2003 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package CMPUT Lecture 4 Slide 2 Outline When things go wrong Throwables, Errors and Exceptions Throwing exceptions Catching exceptions Defining your own exception classes When things go wrong In the last lecture, we learned about pre/post conditions, and assertions. But what if these fail? Java: originally developed for writing software embedded in specialized devices (cell phones, hand-held computers, appliances etc.) Such software must be able to handle unusual situations and manage appropriately when things go wrong CMPUT Lecture 4 Slide 3 CMPUT Lecture 4 Slide 4 Reacting to errors Handling Unusual Situations What if the user enters a word instead of an integer? We try to pop an empty stack? In many languages, the programmer is solely responsible for dealing with errors no help from the language itself we try to divide by zero? We try to read from a file which doesn t exist? We try to access a remote location but the network is down? Should the program produce bad output, or should it crash, or should it try to recover? Code must be written to help identify kinds of errors and how to deal with them convoluted code! Often, methods will return an unusual value such as 1 or null to indicate a failure often difficult to interpret! Java provides some helpful mechanisms to assist us CMPUT Lecture 4 Slide 5 CMPUT Lecture 4 Slide 6 1

2 Exceptions & Errors Java has 2 classes for modeling problems: Error Exception Errors Java.lang.Error models serious, unrecoverable errors such as fatal linkage problems virtual machine errors These errors are not handled and coped with, they usually terminate execution Note that both are subclasses of Throwable Not as common as Exceptions CMPUT Lecture 4 Slide 7 CMPUT Lecture 4 Slide 8 What is an Exception? An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions - Sun Microsystems web site tutorial Not as serious as system errors maybe we can try to recover from them, or at least handle them gracefully Why use exceptions? As we will see in this lecture, the advantages of using exceptions include: separating error-handling code from regular code deferring decisions about how to respond to exceptions providing a mechanism for specifying the different kinds of exceptions that can arise in our program to bear these points in mind as we discuss this material CMPUT Lecture 4 Slide 9 CMPUT Lecture 4 Slide 10 The Exception Mechanism Propagating exceptions When a method wants to signal that a problem has arisen (e.g. a precondition is violated) it throws an exception instead of returning normally. The exception goes to the method that called the method that threw the exception. That method can either Catch (handle) the exception Propagate the exception to the method that called it So an exception will bubble up the call stack until it reaches a method with a suitable handler, or it propagates through the main( ) method (the first method on the call stack) If it is not caught by any method the exception is treated like an error: the stack frames are displayed and the program terminates CMPUT Lecture 4 Slide 11 CMPUT Lecture 4 Slide 12 2

3 Example: Throwing an Exception public Ratio(int top, int bottom) throws Exception{ /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom if (bottom == 0) throw new Exception("Denominator must not be 0"); this.numerator = top; this.denominator = bottom; Throwing Exceptions What can be thrown? Any instance of Throwable or its sublcasses, including Error and Exception Instances of our own specialized exception classes How do we do it? Create an instance, & throw it! throw new Exception( ); throw new Exception( Explanatory message ); CMPUT Lecture 4 Slide 13 CMPUT Lecture 4 Slide 14 Throws clause in method signature The throws clause tells the compiler that a method is a potential source of that type of exception, and that any method that invokes it must be able to deal with it A method must include a throws clause in its signature if it throws an exception itself it might propagate the exception (because it calls another method that might throw an exception that this method cannot catch/handle) public Ratio add(ratio other) throws Exception { /* pre: other is non-null The throws Clause post: return new fraction - the sum of this & other Assert.pre(other!= null, "Other must not be null"); return new Ratio(this.numerator * other.denominator + this.denominator * other.numerator, this.denominator * other.denominator); CMPUT Lecture 4 Slide 15 CMPUT Lecture 4 Slide 16 Throws clause for the main method The signature of the main method must contain a throws clause for any exception that might be thrown by any method it calls (or methods they call, etc.) and not caught. public static void main(string args[])throws Exception{ Ratio r = new Ratio(1,1); // r == 1.0 r = new Ratio(1,2); // r == 0.5 r.add(new Ratio(1,3)); // r still 0.5 r = r.add(new Ratio(1,4)); // r == 0.75 System.out.println(r.value()); // 0.75 printed r = new Ratio(1, 0); // should be an exception Exceptions not Caught If an exception is not caught by any handler, the exception behaves like an error: the program is halted, a message is displayed, and the stack frames are displayed: 0.75_exceptionOccurred: java.lang.exception (Denominator must not be 0) java.lang.exception: Denominator must not be 0 at Ratio.<init>(Ratio.java) at RatioTest.main(RatioTest.java) at com.apple.mrj.jmanager.jmstaticmethoddispatcher.run(jmawtcontextimpl.java) at java.lang.thread.run(thread.java) CMPUT Lecture 4 Slide 17 CMPUT Lecture 4 Slide 18 3

4 Checked/Unchecked Exceptions Diagram Unchecked exceptions: Any exception that is a subclass of java.lang.runtimeexception java.lang.error Not a compile-time error to ignore the possibility of these exceptions we are free to catch them if we want to, but if we don t we re not required to include a throws clause Throwable Exception RuntimeException Any other subclass Error Any subclass Checked exceptions: All other kinds of exceptions must include a throws clause if an exception may occur somewhere inside it Any subclass Any subclass unchecked checked CMPUT Lecture 4 Slide 19 CMPUT Lecture 4 Slide 20 Java s Exception handling When we write a piece of code that we know might produce an exception and we want to catch (handle) the exception, we encapsulate that code in a try block. If no exception is thrown by code within the try block (or the methods that are called within the try block), the code executes normally. If an exception arises in the try block the execution of the try block terminates execution immediately and a catch-clause is sought to handle the exception. Either 1. An appropriate catch clause is found, in which case it is executed, or 2. The exception is propagated to the calling method CMPUT Lecture 4 Slide 21 Example: try-catch public static void main(string args[])throws Exception { Ratio r; r = new Ratio(1, 0); catch (Exception anexception) { System.out.println(anException); r = new Ratio(); // initializes to 0/1 System.out.println( The value is +r.value()); java.lang.exception: Denominator must not be 0 The value is 0.0 can we removed this? CMPUT Lecture 4 Slide 22 Catch clause A catch clause is associated with a particular try block. It will only be used for exceptions that arise within that try block. A catch clause has one parameter the type of this parameter is the type of the exception that this clause can handle. A try statement can have one or more catch clauses, to catch different types of exceptions. Pause for thought Why not just put the exception-handling code in the method where the exception is thrown instead of throwing the exception? Because, different callers may want to handle the same exception differently. For example, the previous segment binds the variable r to a zero Ratio. A different segment might want to bind the variable r to null if an exception occurs. CMPUT Lecture 4 Slide 23 CMPUT Lecture 4 Slide 24 4

5 block Examples // code inside the try block // no catch clause any exceptions that arise in the try block // will propagate to the calling method // code within the try block catch (Exception anexception) { // code that handles any Exception that arises in the try block CMPUT Lecture 4 Slide 25 Multiple Catch Clauses readfromfile( data.txt ); // readfromfile() might generate an exception catch (FileNotFoundException e) { // deal with file_not_found error catch (IOException e) { // deal with errors that occur while reading from file catch (Exception e) { // deal with all other errors what if we put the Exception clause at the top, in front of FileNotFoundException? CMPUT Lecture 4 Slide 26 Java s built-in exception classes Common run-time problems you ve probably seen already: ArrayIndexOutOfBoundsException NullPointerException ArithmeticException NumberFormatException ClassCastException Java provides more than 2 dozen Exceptions to model different kinds of errors and we can write our own too! User-defined Throwable Classes You can define your own Exception subclasses. This allows you to conditionally match only the Exceptions that you want to match. You can also define your own Error subclasses, although this is unusual because normally the exceptions you define will not be unrecoverable. CMPUT Lecture 4 Slide 27 CMPUT Lecture 4 Slide 28 Example: User-defined Exception To define a new type of exception, simply create a subclass of Exception. It will inherit the property of being throwable For example, if we wanted to define our own exception called ZeroDenominator we would define a class called ZeroDenominator in a file called ZeroDenominator.java It could be as simple as this one line public class ZeroDenominator extends Exception{ Throwing a User-defined Exception public Ratio(int top,int bottom) throws ZeroDenominator { /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom if (bottom == 0) throw new ZeroDenominator(); this.numerator = top; this.denominator = bottom; CMPUT Lecture 4 Slide 29 CMPUT Lecture 4 Slide 30 5

6 Catching a User-defined Exception public static void main(string args[]) { Ratio r; r = new Ratio(1, 0); catch (ZeroDenominator anexception) { r = new Ratio(); // initializes to 0/1 System.out.println( The value is +r.value()); Multiple Constructors public class ZeroDenominator extends Exception { public ZeroDenominator(String msg) { super("\nzerodenominator with message " + msg); public ZeroDenominator() { super("\nzerodenominator with no message ); The value is 0.0 CMPUT Lecture 4 Slide 31 CMPUT Lecture 4 Slide 32 finally clause If you want to execute some code whether an exception was raised or not, you can use the optional finally clause Guaranteed to be executed, no matter why we leave the try block It is optional you don t have to have one. Why use finally? The finally clause is useful if you want to perform some kind of clean up operations before exiting the method example: closing down a stream/resource Also avoids duplicating code in each catch clause CMPUT Lecture 4 Slide 33 CMPUT Lecture 4 Slide 34 Full Semantics of try-catch-finally If an expression in the try block throws an exception: the rest of the code in the try block is skipped. If the exception matches the first catch clause the code in its catch block is run the code in the finally clause is run. the rest of the catch clauses are ignored. the rest of the code in the method is run. If the exception does not match the first catch clause, similar actions are taken for the first matching catch clause. CMPUT Lecture 4 Slide 35 Full Semantics of try-catch-finally If the exception does not match any catch clause the code in the finally clause is run all other code in the method is abandoned the exception is thrown to the calling method start looking for some other portion of code that will catch and handle the exception If no exception is thrown at all all code in the try block is executed the code in the finally clause is run normal code in the method following finally is run CMPUT Lecture 4 Slide 36 6

7 Possible Execution Paths (1) Possible Execution Paths (2) 1. No exception occurs 1. Execute the try block 2. Execute the finally clause 3. Execute the rest of the method 1. Exception occurs and is caught 1. Execute the try block until the first exception occurs 2. Execute the first catch clause that matches the exception 3. Execute the finally clause 4. Execute the rest of the method Catch Rest of method Rest of method CMPUT Lecture 4 Slide 37 CMPUT Lecture 4 Slide 38 Possible Execution Paths (3) 3. Exception occurs and is not caught 1. Execute the try block until the first exception occurs 2. Execute the finally clause 3. Propagate the exception to the calling method Throw back Do we deed a different logic? What if we wish to have a cleaner execution Catch Catch Rest of method CMPUT Lecture 4 Slide 39 Q: Can we have either TRY-FINAALY or CATCH-FINALLY? CMPUT Lecture 4 Slide 40 Example: finally & Multiple catches 1 Example: finally & Multiple catches 2 Use a NumberFormatException in the Ratio constructor to signal a zero denominator: public Ratio(int top, int bottom) throws NumberFormatException{ /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom if (bottom == 0) throw new NumberFormatException( "Denominator must not be 0"); this.numerator = top; this.denominator = bottom; CMPUT Lecture 4 code based on Bailey Slide pg Consider a divide method in the class Ratio: public Ratio divide(ratio other) throws Exception { /* pre: other is non-null pre: other is not zero post: return new fraction - the division of this and other if (other == null) throw new NullPointerException(); else if (other.numerator == 0) throw new ArithmeticException(); else return new Ratio(this.numerator*other.denominator, this.denominator*other.numerator); CMPUT Lecture 4 code based on Bailey Slide pg

8 Example: finally & Multiple catches 3 Example: finally & Multiple catches 4 Consider some static method in a class called Tester, that calls the divide method and catches all but one exception (the NumberFormatException): private static void calldivide(ratio top, Ratio bottom) throws Exception{ /* Compute the division of top by bottom and report the answer. If top is null then change it to an invalid ratio 1/0 to generate a NumberFormatException that won't be caught. Catch the other exceptions: bottom is zero or bottom is null. Ratio answer; answer = null; if (top == null) top = new Ratio(1, 0); answer = top.divide(bottom); catch (ArithmeticException anexception) { System.out.println("Arithmetic Except: no div by 0"); answer = new Ratio(); catch (NullPointerException anexception) { System.out.println("NullPointerExcept: no div by null"); answer = new Ratio(); finally { System.out.println(" the answer: " + answer); // rest skipped for NumberFormatException since not caught System.out.println("End method answer: + answer.value()); CMPUT Lecture 4 code based on Bailey Slide pg. 943 CMPUT Lecture 4 code based on Bailey Slide pg. 944 Example: finally & Multiple catches 5 main method illustrating exception handling: public static void main(string args[]) { Tester.callDivide(new Ratio(1, 2), new Ratio(3,4)); // should work Tester.callDivide(new Ratio(1, 2), new Ratio(0,4)); // ArithmeticException caught in calldivide() Tester.callDivide(new Ratio(1, 2), null); // NullPointerException caught in calldivide() Tester.callDivide(null, new Ratio(3,4)); // NumberFormatException NOT caught in calldivide() catch (Exception anexception) { System.out.println("NumberFormatException not caught by calldivide()"); CMPUT Lecture 4 code based on Bailey Slide pg

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State. Revised 01/09/05 About This Lecture Slide # 2 Data Abstraction - Interfaces and Implementations In this lecture we will learn how Java objects and classes can be used to build abstract data types. CMPUT

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

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

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

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

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

More information

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

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

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

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

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer. Exception Handling General idea Checked vs. unchecked exceptions Semantics of throws try-catch Example from text: DataAnalyzer Exceptions [Bono] 1 Announcements Lab this week is based on the textbook example

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

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

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

Internal Classes and Exceptions

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

More information

C16b: Exception Handling

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

More information

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

Data Structures. 02 Exception Handling

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

More information

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

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

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

Errors and Exceptions

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

More information

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

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

What are Exceptions?

What are Exceptions? Exception Handling What are Exceptions? The traditional approach Exception handing in Java Standard exceptions in Java Multiple catch handlers Catching multiple exceptions finally block Checked vs unchecked

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

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. 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

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

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

More information

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

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

CS112 Lecture: Exceptions and Assertions

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

More information

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

Exceptions and Error Handling

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

More information

Programming II (CS300)

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

More information

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

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 - 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

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

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

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

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

More information

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

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

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

More information

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

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

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

More information

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

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

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

Correctness and Robustness

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

More information

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

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

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

CMSC131. Exceptions and Exception Handling. When things go wrong in a program, what should happen. CMSC131 Exceptions and Exception Handling When things go "wrong" in a program, what should happen. Go forward as if nothing is wrong? Try to handle what's going wrong? Pretend nothing bad happened? Crash

More information

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

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

More information

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories Objectives Define exceptions 8 EXCEPTIONS Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 271 272 Exceptions

More information

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

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

More information

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

EXCEPTIONS. Java Programming

EXCEPTIONS. Java Programming 8 EXCEPTIONS 271 Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own 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

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

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions CSE1720 Click to edit Master Week text 01, styles Lecture 02 Second level Third level Fourth level Fifth level Winter 2015! Thursday, Jan 8, 2015 1 Objectives for this class meeting 1. Conduct review of

More information

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

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

Exceptions Handling Errors using Exceptions

Exceptions Handling Errors using Exceptions Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java

More information

COMP1008 Exceptions. Runtime Error

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

More information

EXCEPTION HANDLING. 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 Software Design

Introduction to Software Design CSI 1102 1 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments

More information

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward. Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to

More information

Programming Languages and Techniques (CIS120)

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

More information

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

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

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

More information

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

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance (extends) Use relationship Inheritance 1..n Unidirectional association Inheritance ("extends") Use relationship Implementation ("implements") What is inherited public, protected methods public, proteced attributes What is not inherited

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

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017 PIC 20A Exceptions Ernest Ryu UCLA Mathematics Last edited: November 27, 2017 Introductory example Imagine trying to read from a file. import java.io.*; public class Test { public static void main ( String

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

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

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

Typecasts and Dynamic Dispatch. Dynamic dispatch

Typecasts and Dynamic Dispatch. Dynamic dispatch Typecasts and Dynamic Dispatch Abstract Data Type (ADT) Abstraction Program Robustness Exceptions D0010E Lecture 8 Template Design Pattern Review: I/O Typecasts change the type of expressions as interpreted

More information

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Exceptions: The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception

More information

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

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

More information

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

17. Handling Runtime Problems

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

More information

Chapter 13 Exception Handling

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

More information

Programming Languages and Techniques (CIS120e)

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

More information

Java Errors and Exceptions. Because Murphy s Law never fails

Java Errors and Exceptions. Because Murphy s Law never fails Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter

More information

CMSC 202. Exceptions

CMSC 202. Exceptions CMSC 202 Exceptions Error Handling In the ideal world, all errors would occur when your code is compiled. That won t happen. Errors which occur when your code is running must be handled by some mechanism

More information

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University, International Conference on Informatization in Education, Management and Business (IEMB 2015) Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java Xiaoqing Lv 1 1 huihua

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

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Introduction Unit 4: Input, output and exceptions

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

More information

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 6 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Exceptions An event, which occurs during the execution of a program, that disrupts the normal flow of the program's

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

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

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

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

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