CMSC 202 Exceptions 2nd Lecture.

Slides:



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

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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
Comp 249 Programming Methodology
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.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Chapter 9 Exception Handling Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
CS102--Object Oriented Programming Lecture 11: Exception Handling Copyright © 2008 Xiaoyan Li.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Slides Credit Umair Javed LUMS Web Application Development.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Java Exceptions a quick review….
CMSC 202 Text File I/O.
Lecture 14 Throwing Custom Exceptions
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Tirgul 13 Exceptions 1.
Java Programming Language
Chapter 9 Exception Handling
Exception Handling Chapter 9.
Exceptions & exception handling
Phil Tayco Slide version 1.0 Created Nov. 26, 2017
Advanced Java Programming
CMSC 202 Exceptions.
مظفر بگ محمدی دانشگاه ایلام
Exceptions & exception handling
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
مظفر بگ محمدی دانشگاه ایلام
Abdulmotaleb El Saddik University of Ottawa
Exception Handling Chapter 9 Edited by JJ.
Fundamental Error Handling
CMSC 202 Exceptions 2nd Lecture.
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Chapter 9 Exception Handling
Java Exceptions Dan Fleck CS211.
CMSC 202 Exceptions 2nd Lecture.
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
I/O Exceptions & Working with Files
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

CMSC 202 Exceptions 2nd Lecture

Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit = 500; public BankAccount( ) { balance = 0; } public int getBalance( ) { return balance; } // precondition – amount must be nonnegative an more than min // throws an exception if amount is negative // postcondition – balance updated public int deposit( int amt ) { if (amt < 0 ) throw new DepositNegativeException( ); if (amt < minDeposit) throw new DepositTooSmallException( ); balance += deposit; Oct 2010

Copyright © 2008 Pearson Addison-Wesley. Multiple catch Blocks A try block can call a method that potentially throws any number of exception values, and they can be of differing types In any one execution of a try block, at most one exception can be thrown (since a throw statement ends the execution of the try block) However, different types of exception values can be thrown on different executions of the try block Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 3

Copyright © 2008 Pearson Addison-Wesley. Multiple catch Blocks Each catch block can only catch values of the exception class type given in the catch block heading Different types of exceptions can be caught by placing more than one catch block after a try block Any number of catch blocks can be included, but they must be placed in the correct order Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 4

Multiple catch Blocks public class DepositExample2 { public static void main( String[ ] args ) { BankAccount myAccount = new BankAccount( ); Scanner input = new Scanner( System.in ); System.out.print(“Enter deposit amount: “); int amt = input.nextInt(); try { myAccount.deposit( amt ); System.out.println( “New Balance = “ + myAccount.getBalance()); } catch (DepositNegativeException dne) { // code that “handles” a negative deposit catch (DepositTooSmallException dts) { // code that “handles” a deposit less than the minimum System.out.println (“Have a nice day”); Oct 2010

Catch the More Specific Exception First When catching multiple exceptions, the order of the catch blocks is important When an exception is thrown in a try block, the catch blocks are examined in order The first one that matches the type of the exception thrown is the one that is executed Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 6

Catch the More Specific Exception First public class DepositExample2 { public static void main( String[ ] args ) { BankAccount myAccount = new BankAccount( ); Scanner input = new Scanner( System.in ); System.out.print(“Enter deposit amount: “); int amt = input.nextInt(); try { myAccount.deposit( amt ); System.out.println( “New Balance = “ + myAccount.getBalance()); } catch (Exception e) // OOOPS!! { // code to handle an exception catch (DepositNegativeException dne) { // code that “handles” a negative deposit catch (DepositTooSmallException dts) { // code that “handles” a deposit less than the minimum System.out.println (“Have a nice day”); Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 7

Catch the More Specific Exception First Because a DepositNegativeException and DepositTooSmallException are types of Exception, all exceptions will be caught by the first catch block before ever reaching the second or third block The catch blocks for DepositNegativeException and DepositTooSmallException will never be used! For the correct ordering, simply put the catch block for Exception last. Oct 2010

Declaring Exceptions in a throws Clause If a method can throw an exception but does not catch it, it must provide a warning This warning is called a throws clause The process of including an exception class in a throws clause is called declaring the exception throws AnException //throws clause public int deposit( int amt ) throws DepositNegativeException, DepositTooSmallException { if (amt < 0 ) throw new DepositNegativeException( ); if (amt < minDeposit) throw new DepositTooSmallException( ); balance += deposit; } Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 9

The Catch or Declare Rule Most ordinary exceptions that might be thrown within a method must be accounted for in one of two ways: The code that can throw an exception is placed within a try block, and the possible exception is caught in a catch block within the same method The possible exception can be declared at the start of the method definition by placing the exception class name in a throws clause Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 10

Checked and Unchecked Exceptions Exceptions that are subject to the catch or declare rule are called checked exceptions The compiler checks to see if they are accounted for with either a catch block or a throws clause The classes Throwable, Exception, and all descendants of the class Exception (with the exception of RuntimeException and its subclasses) are checked exceptions All other exceptions are unchecked exceptions The class Error and all its descendant classes are called error classes Error and RuntimeException classes are not subject to the Catch or Declare Rule [M] Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 11

Hierarchy of Throwable Objects Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 12

Exceptions to the Catch or Declare Rule Checked exceptions must follow the Catch or Declare Rule Programs in which these exceptions can be thrown will not compile until they are handled properly Unchecked exceptions are exempt from the Catch or Declare Rule Programs in which these exceptions are thrown simply need to be corrected, as they result from some sort of error Even if an exception is unchecked, you can still catch if if you want [M] Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 13

Runtime Exceptions Runtime exceptions are Unchecked Probably a bug in your program Referencing a null pointer Array index out of bounds Thrown automatically by Java Oct 2010

What Happens If an Exception is Never Caught? If every method up to and including the main method simply includes a throws clause for an exception, that exception may be thrown but never caught In a GUI program (i.e., a program with a windowing interface), nothing happens - but the user may be left in an unexplained situation, and the program may be no longer be reliable In non-GUI programs, this causes the program to terminate with an error message giving the name of the exception class Every well-written program should eventually catch every exception by a catch block in some method Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 15

Copyright © 2008 Pearson Addison-Wesley. The finally Block The finally block contains code to be executed whether or not an exception is thrown in a try block If it is used, a finally block is placed after a try block and its following catch blocks try { . . . } catch( ExceptionClass1 e ) . . . catch( ExceptionClassN e ) finally { CodeToBeExecutedInAllCases } Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 16

Copyright © 2008 Pearson Addison-Wesley. The finally Block If the try-catch-finally blocks are inside a method definition, there are three possibilities when the code is run: The try block runs to the end, no exception is thrown, and the finally block is executed An exception is thrown in the try block, caught in one of the catch blocks, and the finally block is executed An exception is thrown in the try block, there is no matching catch block in the method, the finally block is executed, and then the method invocation ends and the exception object is thrown to the enclosing method Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 17

When to use a finally block The finally block should contain code that you always want to run whether or not an exception occurred. Generally the finally block contains code to release resources other than memory Close files Close internet connection Clear the screen Oct 2010

Exception Controlled Loops Sometimes it is better to simply loop through an action again when an exception is thrown, as follows. We’ll see a real example next. boolean done = false; while ( ! done ) { try CodeThatMayThrowAnException done = true; } catch ( SomeExceptionClass e ) SomeMoreCode Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 19

Exceptions with the Scanner Class The nextInt method of the Scanner class can be used to read int values from the keyboard However, if a user enters something other than a well-formed int value, an InputMismatchException will be thrown Unless this exception is caught, the program will end with an error message If the exception is caught, the catch block can give code for some alternative action, such as asking the user to reenter the input Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 20

The InputMismatchException The InputMismatchException is in the standard Java package java.util A program that refers to it must use an import statement, such as the following: import java.util.InputMismatchException; It is a descendent class of RuntimeException Therefore, it is an unchecked exception and does not have to be caught in a catch block or declared in a throws clause However, catching it in a catch block is allowed, and can sometimes be useful Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 21

An Exception Controlled Loop ( 1 of 3) Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 22

An Exception Controlled Loop ( 2 of 3) Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 23

An Exception Controlled Loop ( 3 of 3) Oct 2010 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 24