CS102--Object Oriented Programming

Slides:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

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)
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Exception Handling Chapter 8. Outline Basic Exception Handling Defining Exception Classes Using Exception Classes.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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 ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
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.
Exception handling Dealing with life’s little surprises.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS102--Object Oriented Programming Lecture 11: Exception Handling Copyright © 2008 Xiaoyan Li.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Java Exception Handling
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.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
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.
Java Programming: Guided Learning with Early Objects
COMP Exception Handling Yi Hong June 10, 2015.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
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.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Chapter 8-Exception Handling/ Robust Programming.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
Chapter 16 Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Chapter 9 Exception Handling
Exception Handling Chapter 9.
Exceptions & exception handling
Exceptions & exception handling
Exception Handling Chapter 9 Edited by JJ.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Chapter 9 Exception Handling
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.
Chapter 12 Exception Handling and Text IO Part 1
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Presentation transcript:

CS102--Object Oriented Programming Lecture 12: More on Exception Handling Copyright © 2008 Xiaoyan Li

Review:Exception Handling Throwing an exception / Handling an exception The basic way of handling exceptions in Java consists of the try-throw-catch trio/ mechanism . . . // method code try { . . . throw new Exception(StringArgument); } catch(Exception e) } . . . Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Review: Exception Handling When a try block is executed, how does it change the flow of control : No exception is thrown in the try block The code in the try block is executed to the end of the block The catch block is skipped The execution continues with the code placed after the catch block An exception is thrown in the try block and caught in the catch block The rest of the code in the try block is skipped Control is transferred to a following catch block (in simple cases) The thrown object is plugged in for the catch block parameter The code in the catch block is executed The code that follows that catch block is executed (if any) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Review:Exception Classes There are more exception classes than just the single class Exception All predefined exception classes have the following properties: There is a constructor that takes a single argument of type String The class has an accessor method getMessage that can recover the string given as an argument to the constructor when the exception object was created All programmer-defined classes should have the same properties Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Review: Exception Classes from Standard Packages Numerous predefined exception classes are included in the standard packages that come with Java For example: IOException NoSuchMethodException FileNotFoundException Many exception classes must be imported in order to use them import java.io.IOException; The class Exception is in the java.lang package, and so requires no import statement Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Using the getMessage Method . . . // method code try { . . . throw new Exception(StringArgument); } catch(Exception e) String message = e.getMessage(); System.out.println(message); System.exit(0); } . . . Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Review: A Programmer-Defined Exception Class Copyright © 2008 Pearson Addison-Wesley. All rights reserved

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

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 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The throws Clause in Derived Classes When a method in a derived class is overridden, it should have the same exception classes listed in its throws clause that it had in the base class Or it should have a subset of them A derived class may not add any exceptions to the throws clause But it can delete some Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copyright © 2008 Pearson Addison-Wesley. All rights reserved When to Use Exceptions Exceptions should be reserved for situations where a method encounters an unusual or unexpected case that cannot be handled easily in some other way When exception handling must be used, here are some basic guidelines: Include throw statements and list the exception classes in a throws clause within a method definition Place the try and catch blocks in a different method Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copyright © 2008 Pearson Addison-Wesley. All rights reserved When to Use Exceptions Here is an example of a method from which the exception originates: public void someMethod() throws SomeException { . . . throw new SomeException(SomeArgument); } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copyright © 2008 Pearson Addison-Wesley. All rights reserved When to Use Exceptions When someMethod is used by an otherMethod, the otherMethod must then deal with the exception: public void otherMethod() { try someMethod(); . . . } catch (SomeException e) CodeToHandleException Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Nested try-catch Blocks It is possible to place a try block and its following catch blocks inside a larger try block, or inside a larger catch block If a set of try-catch blocks are placed inside a larger catch block, different names must be used for the catch block parameters in the inner and outer blocks, just like any other set of nested blocks If a set of try-catch blocks are placed inside a larger try block, and an exception is thrown in the inner try block that is not caught, then the exception is thrown to the outer try block for processing, and may be caught in one of its catch blocks Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copyright © 2008 Pearson Addison-Wesley. All rights reserved 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 } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copyright © 2008 Pearson Addison-Wesley. All rights reserved 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 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Rethrowing an Exception A catch block can contain code that throws an exception Sometimes it is useful to catch an exception and then, depending on the string produced by getMessage (or perhaps something else), throw the same or a different exception for handling further up the chain of exception handling blocks Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Exception Handling 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 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

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 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

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

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

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

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

ArrayIndexOutOfBoundsException An ArrayIndexOutOfBoundsException is thrown whenever a program attempts to use an array index that is out of bounds This normally causes the program to end Like all other descendents of the class RuntimeException, it is an unchecked exception There is no requirement to handle it When this exception is thrown, it is an indication that the program contains an error Instead of attempting to handle the exception, the program should simply be fixed Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Exercise 1: Here is a snippet of code that inputs two integers and divides them. Scanner scan = new Scanner(System.in); int n1, n2; double r; n1 = scan.nextInt(); n2 = scan.nextInt(); r = (double)n1/n2; Place this code into a try-catch block with multiple catches so that different error messages are printed if we attempt to divide by zero or if the user enters textual data instead of integers (java.util.InputMismatchException). If either of these conditions occurs then the program should loop back and let the user enter new data.

Exercise 2: Modify the previous exercise so that the snippet of code is placed inside a method. The method should be named ReturnRatio and read the input from the keyboard and throw different exceptions for divide by zero or input mismatch between text and an integer. Create your own exception class for divide by zero. Invoke ReurnRatio from your main method and catch the exceptions in main. The main method should invoke the invoke the ReturnRatio method again if any exception occurs.

Summary on Exception Handling When do you want to use exceptions? How to use exceptions?

Announcement: Programming Assignment 6 Page 557 Project 1. Due on Thursday April 10th Next Lecture: File I/O – Chapter 10