An exception is simply an error. Instead of saying an error occurred, we say that an.

Similar documents
Full file at Chapter 2 - Inheritance and Exception Handling

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

ITI Introduction to Computing II

ITI Introduction to Computing II

Exceptions - Example. Exceptions - Example

16-Dec-10. Consider the following method:

Input from Files. Buffered Reader

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Programming II (CS300)

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Programming II (CS300)

Input-Output and Exception Handling

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

11/1/2011. Chapter Goals

COMP-202 Unit 9: Exceptions

Exception-Handling Overview

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

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

COMP1008 Exceptions. Runtime Error

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

More on Exception Handling

Assignment 17 Deadline: Oct pm COSC211 CRN15376 Session 14 (Oct. 29)

CSPP : Introduction to Object-Oriented Programming

School of Informatics, University of Edinburgh

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP-202 Unit 9: Exceptions

Java Input/Output. 11 April 2013 OSU CSE 1

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

CS112 Lecture: Exceptions and Assertions

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

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

Here is a hierarchy of classes to deal with Input and Output streams.

BBM 102 Introduction to Programming II Spring Exceptions

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

Introductory Programming Exceptions and I/O: sections

Intro to Computer Science II. Exceptions

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

More on Exception Handling

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

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

AP Computer Science A

Errors and Exceptions

Example Program. public class ComputeArea {

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

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Std 12 Lesson-10 Exception Handling in Java ( 1

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Fundamentals of Object Oriented Programming

Elementary Programming

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

CMSC 202. Exceptions

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

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

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Recitation: Loop Jul 7, 2008

CS1083 Week 2: Arrays, ArrayList

When we reach the line "z = x / y" the program crashes with the message:

CS159. Nathan Sprague

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

Text User Interfaces. Keyboard IO plus

Java Programming Unit 7. Error Handling. Excep8ons.

1. Download the JDK 6, from

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

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

CS244 Advanced Programming Applications

Exceptions. CSC207 Winter 2017

Java Errors and Exceptions. Because Murphy s Law never fails

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

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

Simple Java Input/Output

Computer Science is...

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

Abstract Classes, Exceptions

Class, Variable, Constructor, Object, Method Questions

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

Chapter 11: Exceptions and Advanced File I/O

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

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

Object-Oriented Design. March 2005 Object Oriented Design 1

CSCI 1103: File I/O, Scanner, PrintWriter

Sri Vidya College of Engineering & Technology Question Bank

ECE 122. Engineering Problem Solving with Java

What are Exceptions?

Typecasts and Dynamic Dispatch. Dynamic dispatch

CS159. Nathan Sprague

CIS 110: Introduction to Computer Programming

Exceptions and Design

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

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

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


Unit 10: exception handling and file I/O

Chapter 12 Exception Handling

Transcription:

3-1 An exception is simply an error. Instead of saying an error occurred, we say that an. Suppose we have a chain of methods. The method is the first in the chain. An expression in it calls some other method, and an expression in it calls yet another. Let s assume some piece of code deep in this chain throws an exception. The code immediately surrounding the offending code is examined for a statement. (More on this later; however, for now, suffice it to say that if a is present, it handles the error gracefully without the entire program coming to a halt). If no is found, control immediately passes up the chain to the code that called the method in which the error just occurred. Again, a statement is sought, and if none is found, control is passed back up the calling chain one level. This continues until the method is reached. If it has no, the program is halted with a trace of the method calls, the type of exception, and its error message. Actually, the above is oversimplified just a bit. In the absence of a statement, control is passed up the calling chain one level. This is done with a specifier in the method signature. (More on on the next pg) You can as in the following example from a object. In this example we look at that we require before this method is called. The method we will discuss is. Certainly, we can t withdraw more than what we have in the account. Also, it would be meaningless to withdraw a negative or zero amount, so we detail these preconditions in the rems above the method signature. /* precondition: amount <= balance * precondition: amount > 0 */ public void withdraw(double amount) if (amount > balance) String s = Can t withdraw more than the balance. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; // if (amount <= 0) String s = Withdrawal amount must be greater than 0. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; //... remainder of code for this method...

In the above code we used the exception class,. See Appendix K for a list of some other exception classes. those that Java requires handling by the programmer. These are typically errors over which the programmer has no control. The IOException is a classic example. 3-2 For errors that are out of your control, such as an due to a corrupt file, etc., Java is and for errors for you. those that the programmer may or may not handle. These are errors that are the programmer s fault. A typical example would be a division by 0 giving an. Another example would be a that might occur when you try to do and the can t convert to an. (The example code on the previous page concerned unchecked exceptions.) Now let s suppose we have a method that has the of throwing a exception. We the exception with one of two choices. Notice that with checked exceptions, doing nothing is a choice, it won t even compile unless you do one of the following: 1. Handle the exception with as we will see later in this lesson. 2. Put a (or some other appropriate checked exception) tag on the method signature as in the following example: public void readthedisk( ) code that uses a file reader might encounter a corrupt file So, what s the purpose of this specifier in a method? The is so the calling-method (the method that called the method) is signaled that an occur in and that the calling method is to handle the exception. Of course, in the calling-method you can make the choice of putting another specifier in signature, or to actually handle the exception right there with,, and. Thus, we see that the specifier is a way to the handling of an exception. We can keep postponing the actual handling of the exception right up the calling chain. Of course we can defer it all the way up to the method and if no is there, then the program terminates. The specifier can provide for exceptions as in the following example:

3-3 public void amethod(int x) throws IOException, ClassNotFoundException We should also mention that unchecked exceptions can also make use of to defer handling of the exception or you can handle them at any level in the calling chain with and. Unchecked exceptions need not be handled at all. You can just let the program terminate (crash) immediately upon detection of such an error. (referred to above as handling the exception): public class MyClass public void mymethod(double d) some code in which you are not worried about an exception occurring. try // some code where you might expect an exception String s = in.nextline( ); // int x = Integer.parseInt(s); // // more code catch (IOException e) System.out.println( Input/output error + e); // Continues execution after last catch below. catch (NumberFormatException e) System.out.println( Input was not a num + e); // Continues execution immediately after this catch. code execution continues here after try block is finished or, if an exception occurs, execution continues here after catch block finishes

3-4 (this block is optional) try catch( ) finally This block of code is to execute, regardless of whether there was an exception or not. This is, such as closing a file or releasing a network connection. If an exception occurs in the block and none of the statements are appropriate to handle the exception, control passes to this block and the code here executes then the exception is actually thrown and passed up the calling chain where we can attempt to it. Even if a block throws an exception of its own, control is still passed to the block. if (amount > balance) GoofyException e = new GoofyException( You made a dumb mistake! ); throw e; public class GoofyException public GoofyException( ) // It is customary to provide a default constructor, // even if empty. public GoofyException(String reason) //Your own constructor super(reason); 1. If you use the following two statements, they must go in the order shown subclass on the top, superclass on the bottom. (Note that is a subclass of )

3-5 catch(filenotfoundexception e) System.out.println("FileNotFound"); catch(ioexception e) System.out.println("IOException"); In this particular case, if the block generated a, only FileNotFound would be printed. The second would be ignored. 2. If you have a method that throws an up to the next level in the calling chain, we should be aware that in addition to being thrown to the next level, all its subclasses are also thrown to the next level in the chain. 3. If you put a inside a block of code (such as those belonging to loops and statements), then the corresponding statements must also reside in that same block. 4. It is permissible to have and blocks without a block. 5. If there is a block, there must be at least a block.

3-6 1. Rewrite the method below so as to consolidate the two error messages (that signal violation of preconditions) into a single error message. /* * precondition: amount <= balance * precondition: amount > 0 */ public void withdraw(double amount) if (amount > balance) String s = Can t withdraw more than the balance. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; // if (amount <= 0) String s = Withdrawal amount must be greater than 0. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; //... remainder of code for this method... 2. Write a method called. Its signature is: public void setstudentscore(int score) You need not worry about the bulk of the code inside this method. Establish some preconditions on the score parameter and detail those preconditions in rems up above the signature. Then, just inside the code body, throw an if the preconditions are not met. 3. In Java we don t say, The program generated an error ; rather, we say what? 4. What are the two types of exceptions? 5. Which type of exception requires being handled? 6. What are the two ways to handle checked exceptions?

3-7 7. Is it permissible for unchecked exceptions to be handled with or with? 8. Give an example of a checked exception and what conditions might cause it. 9. Give an example of a unchecked exception and what conditions might cause it. 10. Modify the following method, so that if an occurs, the actual handling of that exception with is deferred one layer up the calling chain. public String car(int xs) some code that might produce an 11. Modify the following method, so that if an occurs, the handling of that exception with is handled in this method. public String car(int xs) some code that might produce an 12. Create your own exception type by creating a class called. 13. Write code that will use the above class by creating an object with it. Specify the error announcement with Hey, you messed up and then throw the exception.

3-8 1. What is output by the code to the right on the input below? big mamma 2 A. mamma B. big mamma C. g D. i E. big mamma2 2. What is output by the code to the right on the input below? big mamma 22 A. b B. Error: 22 C. a D. Nothing 3. Which of the following replaces in the code to the right to make it do what the remarks suggest? A. prd = 1; B. return 1; C. System.exit( ); D. No code is needed 4. Assume has been filled in correctly. What is returned by? A. 10 B. 5 C. 1 D. 2 5. What is output by the code to the right if the method called encounters the following line of code? Assume the signature includes. int j = Integer.parseInt( Two Thousand ); A. Nothing B. Error with number format Error C. Error with number format D. Error //Assume nextline( ) and nextint( ) are static methods in //a class named Scanner that reads a String and an integer //from the keyboard. Scanner rdr = new Scanner(System.in); String str = rdr.nextline( ); int j = rdr.nextint( ); try System.out.print( str.charat(j) ); catch(stringindexoutofboundsexception e) System.out.print( Error: + j); //Returns the product of two integers represented as //strings. If either string is not a number, returns the other //number. If both are not numbers, returns 1. public static int product(string str1, String str2) int prd = 1; try prd*=integer.parseint(str1); catch(numberformatexception) try prd*=integer.parseint(str2); catch(numberformatexception) return prd; try test( ); catch(numberformatexception e) System.out.println( Error with number format ); catch(runtimeexception e) System.out.println( Error );

3-9 6. If the code designated by to the right does not throw any exceptions, which of the remaining code sections will execute? A. B. and (if no errors in ) D. and 7. What exceptions thrown by method are passed up the calling chain? A. All exceptions B. IOException C. IOException, its subclasses, and unchecked exceptions D. IOException and its subclasses 8. Suppose the method does not include a or. Futhermore, the code which inputs disk values may throw an. Which of these should replace in the code to the right? try catch(runtimeexception e) finally public static void mental( ) throws IOException // code not shown public static void main(string[] args) // input some values from disk A. throws IOException B. throw IOException C. throws new IOException D. extends IOException 9. Which of these is not a keyword in Java? A. short B. continue C. finally D. final

3-10 Create a new project called that will contain two classes, and. Create the class by modifying your (see Lesson 2) project as follows: import java.io.*; //necessary for File and IOException import java.util.*; //necessary for Scanner public class public static void readthefile(string filename) throws IOException Scanner sf = new Scanner(new File("C:\\temp_Name\\" + filename)); int maxindx = -1; //-1 so when we increment below, the first index is 0 String text[] = new String[100]; //declare more than we need while(sf.hasnext( )) maxindx++; text[maxindx] = sf.nextline( ); //maxindx is now the highest index of text[], = -1 if no lines of text. sf.close( ); //we opened file so we must close it for (int j = 0; j <= maxindx; j++) System.out.println(text[j]); Now create a class with a method in which you repeatedly loop while inputting a file name from the keyboard. Also, inside the loop call the method of the class and pass the file name input from the keyboard as a parameter. Set up a pair in so as to keep looping if passes an up the calling chain. If everything in completes successfully, then in release from the loop and output It worked. Provide for an escape from the loop by informing the user that he can enter the word exit. This should provide a release from the loop and print It did not work.