Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

Slides:



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

Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Self-Reference - Induction Cmput Lecture 7 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Data Abstraction - Interfaces and Implementations Cmput Lecture 1 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Code Clarity - Comments, Preconditions and Postconditions Cmput Lecture 2 Department of Computing Science University of Alberta ©Duane Szafron 1999.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Fundamental Error Handling
Web Design & Development Lecture 7
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Exceptions Cmput Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Revised 12/16/99

©Duane Szafron About This Lecture In this lecture we learn how to use Java Exceptions to handle unusual program conditions. Note, this material is not in the text book.

©Duane Szafron Outline Assertions and generic exceptions Throwables, Errors and Exceptions Throwing exceptions Catching exceptions Exception matching User-defined Throwable classes Multiple catch clauses and the finally clause

©Duane Szafron Exceptions - Failed Assertions An assertion is a condition that should be true. What happens if the assertion fails? One option is to report that the assertion has failed and to halt the program. (Preventive Approach) Alternately, the programmer can signal that an unusual event has occurred and call some code to handle the special case. (Corrective Approach) In general, these special cases are generically called Exceptions.

©Duane Szafron Quick Example Want to determine the number of pretzels per glass of beer Enter number of pretzels: 12 Enter number of glasses of beer: 5 12 pretzels 5 glasses of beer We have 2.4 pretzels for each glass of beer.

©Duane Szafron Quick Example Want to determine the number of pretzels per glass of beer Enter number of pretzels: 13 Enter number of glasses of beer: 0 No Beer! Go get some at RAT’s Program aborted.

©Duane Szafron GotBeer (1 of 2) Public class GotBeer { public static void main(String[ ] args) { int beerCount, pretzelCount; double pretzelsPerGlass; System.out.println(“Enter number of pretzels:”); pretzelCount = Savit.readLineInt( ); System.out.println(“Enter number of glasses of beer:”); beerCount = Savit.readLineInt( ); if (beerCount <= 0) { System.out.printlin(“No Beer!”); System.out.println(“Go to RAT’s”); System.out.println(“Program Aborted”); System.exit(0); } Assert.condition(beerCount>0, “No Beer!\nGo to RAT\’s\nProgramAborted”); }

©Duane Szafron GotBeer (1 of 2) pretzelsPerGlass = pretzelCount/(double)beerCount; System.out.prtintln(pretzelCount + “ pretzels.”); System.out.prtintln(beerCount + “ glasses of beer.”); System.out.prtintln(“You have “ + pretzelsPerGlass + “ pretzels for each glass of beer.”); }

©Duane Szafron GotBeer with Exceptions (1 of 2) Public class GotBeer { public static void main(String[ ] args) { int beerCount, pretzelCount; double pretzelsPerGlass; try { System.out.println(“Enter number of pretzels:”); pretzelCount = Savit.readLineInt( ); System.out.println(“Enter number of glasses of beer:”); beerCount = Savit.readLineInt( ); if (beerCount <= 0) throw new Exception(“No Beer!);

©Duane Szafron GotBeer with Exceptions (1 of 2) pretzelsPerGlass = pretzelCount/(double)beerCount; System.out.prtintln(pretzelCount + “ pretzels.”); System.out.prtintln(beerCount + “ glasses of beer.”); System.out.prtintln(“You have “ + pretzelsPerGlass + “ pretzels for each glass of beer.”); } // End of “try” block. Catch(Exception e) { System.out.println(e.getMessage()); //”No Beer!” System.out.println(“Go to RAT’s”); System.out.println(“Program Aborted”); System.exit(0); } } } //End of “main”

©Duane Szafron Generic Exceptions in Java In Java, the generic concept of an exception is represented by a class called Throwable. In Java, a throw statement is used to signal an unusual situation in a program. The Java syntax is: throw In Java, there are two subclasses of the Throwable class, Error and Exception. However, Java errors and exceptions are both considered exceptions in the generic sense.

©Duane Szafron The throws Statement A throws statement is used to signal that an generic exception (Java exception or Java error) has occurred. The syntax of a throws statement is: throws The is any expression that evaluates to an object that is an instance of the Throwable class or any subclass.

©Duane Szafron Throwing an Error An Error is used when the program should be halted. code based on Bailey pg. 8 For example, we could modify our Ratio constructor: public Ratio(int top, int bottom) { /* pre: bottom != 0 post: constructs a ratio equivalent to top/bottom */ //Assert.pre(bottom != 0, "Denominator must not be 0"); if (bottom == 0) throw new Error(“Denominator must not be 0”); this.numerator = top; this.denominator = bottom; }

©Duane Szafron An Error Halts the Program halted When an error is thrown, the program is halted, a message is displayed, and the stack frames are displayed: _exceptionOccurred: java.lang.Error (Denominator must not be 0) java.lang.Error: Denominator must not be 0 at Ratio. (Ratio.java) at RatioTest.main(RatioTest.java) at com.apple.mrj.JManager.JMStaticMethodDispatcher.run(JM AWTContextImpl.java) at java.lang.Thread.run(Thread.java) detailed application

©Duane Szafron Exceptions An Exception is used when some special code may be used to handle the exception. Every method that throws an exception must either catch (handle) the exception or pass the exception back to calling method using a throws clause in its method signature. When an exception is thrown, the java interpreter looks for an exception handler.

©Duane Szafron Throwing an Exception For example: 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; } code based on Bailey pg. 8

©Duane Szafron The throws Clause Each using method of the method that throws an exception must also either catch the exception or have a throws clause in its signature to throw it to its caller: public Ratio add(Ratio other) throws Exception { /* pre: other is non-null post: return new fraction - the sum of this and 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); } code based on Bailey pg. 8

©Duane Szafron Chaining throws clauses 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 } code based on Bailey pg. 9 Eventually either the Exception must be caught or the signature of the main method must contain a throws clause:

©Duane Szafron Exceptions not Caught halted 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: _exceptionOccurred: java.lang.Exception (Denominator must not be 0) java.lang.Exception: Denominator must not be 0 at Ratio. (Ratio.java) at RatioTest.main(RatioTest.java) at com.apple.mrj.JManager.JMStaticMethodDispatcher.run(JMAWT ContextImpl.java) at java.lang.Thread.run(Thread.java)

©Duane Szafron The try-catch-finally statement A try-catch-finally statement is used to catch an exception (and therefore to prevent program termination). The EBNF Java syntax is: try { } [ ]; Recall that in Extended BNF, { } means zero or more occurrences and that [ ] means an optional occurrence. The is just a compound statement.

©Duane Szafron The catch clause The Java syntax for a catch clause is: catch ( ) The is just a compound statement. The declares the classes of exception that will be caught. Its syntax is:

©Duane Szafron Simple Example Syntax Here is the syntax for a simple example with one catch clause and no finally clause: try { r = new Ratio(x, y); /*... more statements... */ } catch (Exception anException) { System.out.println(anException); r = new Ratio(); // initializes to 0/1 } code based on Bailey pg. 9 1: If y=0 & if no catch clause, Exit 3 See slide16 for where throws takes place enhanced 2 y ~= 0 y = 0

©Duane Szafron Semantics for Simple try-catch 1 If an expression in the try block of a statement with one catch clause and no finally clause throws an exception: –the rest of the code in the try block is skipped. –If the exception “matches” the catch clause, the statements in the catch block are run, followed by the rest of the method (case 3). –If the exception does not match the catch clause, the rest of code in the method is skipped and the exception is thrown to the calling method (case 1).

©Duane Szafron Semantics for Simple try-catch 2 If an expression in the try block does not throw an exception (case 2): –The catch clause is skipped. –The rest of the method is run normally. If you put a try-catch-finally statement around a method that may generate an exception, you can remove the throws clause in the calling method’s signature.(Why?... because you are handling the exception in the method with the Catch phrase.)

©Duane Szafron Example: try-catch For example: public static void main(String args[ ]) throws Exception { Ratio r; try { r = new Ratio(1, 0); } catch (Exception anException) { System.out.println(anException); r = new Ratio(); // initializes to 0/1 } System.out.println(r); } can be removed code based on Bailey pg. 9 java.lang.Exception: Denominator must not be (Note... See slide 10)

©Duane Szafron Why Use Exceptions? Why not just put the exception 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.

©Duane Szafron Exception Matching When does a thrown exception “match” a catch clause? –The thrown exception has a class. –The variable in the exception declaration of the catch clause has a declared class. –They “match” if class of the thrown exception is the same as the declared class in the catch clause or is one of its subclasses.

©Duane Szafron Example: Exception Matching 1 For example if the thrown exception class is a NumberFormatException: 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; } code based on Bailey pg. 8 It can be caught by a NumberFormatException or any of its superclasses:

©Duane Szafron Example: Exception Matching 2 public static void main(String args[ ]) { Ratio r; try { r = new Ratio(1, 0); } catch (NumberFormatException anException) { // or IllegalArgumentException or RuntimeException or // Exception System.out.println(anException); r = new Ratio(); // initializes to 0/1 } System.out.println(r); } java.lang.NumberFormatException: Denominator must not be code based on Bailey pg. 8

©Duane Szafron Throwable Inheritance Hierarchy Object Error Throwable Exception LinkageClassNotFoundRuntime IllegalThreadState IllegalArgumentIndexOutOfBound NumberFormat User-Defined?

©Duane Szafron 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 you cannot use them to “catch” errors.

©Duane Szafron Example: User-defined Errors 1 For example, the implementation of the Assert class, uses a new error subclass: code from Bailey structure package static public void pre(boolean test, String message) // pre: result of precondition test. // post: does nothing if test true, otherwise abort w/message { if (test == false) throw new FailedPrecondition(message); }

©Duane Szafron Example: User-defined Errors 2 class FailedAssertion extends Error { public FailedAssertion(String reason) // post: constructs a new failed assertion error { super("\nAssertion that failed: " + reason); } code from Bailey structure package class FailedPrecondition extends FailedAssertion { public FailedPrecondition(String reason) // post: constructs a new failed precondition { super("\nA precondition: " + reason); } } overrides Error Failed Assertion Failed Precondition subclass of

©Duane Szafron “finally” and Multiple catches You can put multiple catch clauses in the try statement to handle different kinds of exceptions in different ways. If you want to execute some code, whether an exception was raised or not, you can use the optional finally clause. The syntax of a finally clause is: finally The is just a compound statement.

©Duane Szafron Full Semantics of try-catch-finally 1 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 optional 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.

©Duane Szafron Full Semantics of try-catch-finally 2 –If the exception does not “match” the first catch clause, similar actions are taken for the first “matching” catch clause. –If the exception does not “match” any catch clause the optional code in the finally clause is run all other code in the method is abandoned the exception is thrown to the calling method.

©Duane Szafron Example: finally & Multiple catches 1 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); } } code based on Bailey pg. 9

©Duane Szafron Example: finally & Multiple catches 2 public static void main(String args[ ]) { try { UseRatio.divide(new Ratio(1, 2), new Ratio(3,4)); // should work UseRatio.divide(new Ratio(1, 2), new Ratio(0,4)); // ArithmeticException caught in UseDivide() UseRatio.divide(new Ratio(1, 2), null); // NullPointerException caught in UseDivide() UseRatio.divide(null, new Ratio(3,4)); // NumberFormatException NOT caught in UseDivide() } catch (Exception anException) { System.out.println("NumberFormatException not caught by divide()"); } } code based on Bailey pg. 9

©Duane Szafron Example: finally & Multiple catches 3 private static void divide(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; try { if (top == null) top = new Ratio(1, 0); //Doesn’t make sense but throws // NumberFormat Exception answer = top.divide(bottom); } code based on Bailey pg. 9

©Duane Szafron Example: finally & Multiple catches 4 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("Finally the answer: " + answer); } // rest skipped for NumberFormat Exception since not caught System.out.println("End method answer: ” + answer.value()); } code based on Bailey pg. 9