CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

Similar documents
Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Motivations. Chapter 12 Exceptions and File Input/Output

Chapter 13 Exception Handling

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Chapter 12 Exception Handling

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

C17a: Exception and Text File I/O

Exception-Handling Overview

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

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring 2017

ECE 122. Engineering Problem Solving with Java

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

What is a Computer? Chapter 1-9, 12-13, 18, 20, 23 Review Slides

Chapter 1-9, 12-13, 18, 20, 23 Review Slides. What is a Computer?

Correctness and Robustness

Programming II (CS300)

Programming II (CS300)

Lecture 19 Programming Exceptions CSE11 Fall 2013

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Data Structures. 02 Exception Handling

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

Introduction to Programming Using Java (98-388)

Input-Output and Exception Handling

CS159. Nathan Sprague

abstract binary class composition diamond Error Exception executable extends friend generic hash implementation implements

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Sri Vidya College of Engineering & Technology Question Bank

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

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

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

Object Oriented Programming. Week 7 Part 1 Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions

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

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

ing execution. That way, new results can be computed each time the Class The Scanner

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

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

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

COE318 Lecture Notes Week 10 (Nov 7, 2011)

EXCEPTION HANDLING. Summer 2018

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

Reading Input from Text File

11/1/2011. Chapter Goals

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CSCI 261 Computer Science II

Programming Languages and Techniques (CIS120)

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

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

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

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

Errors and Exceptions

Defensive Programming. Ric Glassey

Java Exception. Wang Yang

Exceptions Handling Errors using Exceptions

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

17. Handling Runtime Problems

Pace University. Fundamental Concepts of CS121 1

CC316: Object Oriented Programming

Introduction Unit 4: Input, output and exceptions

Object Oriented Programming

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Exceptions, Case Study-Exception handling in C++.

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Intro to Computer Science II. Exceptions

Exception Handling in Java

Full file at Chapter 2 - Inheritance and Exception Handling

COMP1008 Exceptions. Runtime Error

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

14. Exception Handling

16-Dec-10. Consider the following method:

CS Programming I: Exceptions

School of Informatics, University of Edinburgh

CS Programming I: Exceptions

Internal Classes and Exceptions

GPolygon GCompound HashMap

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

6.Introducing Classes 9. Exceptions

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

Object Oriented Programming

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

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

Programming Languages and Techniques (CIS120)

ITI Introduction to Computing II

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

Introductory Programming Exceptions and I/O: sections

Java Errors and Exceptions. Because Murphy s Law never fails

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

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

Program Correctness and Efficiency. Chapter 2

Comp 249 Programming Methodology Chapter 9 Exception Handling

ITI Introduction to Computing II

CS159. Nathan Sprague

Exceptions. CSC207 Winter 2017

CS 11 java track: lecture 3

Transcription:

CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO rights reserved. 2

Motivation 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 terminate gracefully? This is the subject we will introduce in this chapter rights reserved. 3 Objectives To get an overview of exceptions and exception handling ( 12.2). To explore the advantages of using exception handling ( 12.2). To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked ( 12.3). To declare exceptions in a method header ( 12.4.1). To throw exceptions in a method ( 12.4.2). To write a try-catch block to handle exceptions ( 12.4.3). To explain how an exception is propagated ( 12.4.3). To obtain information from an exception object ( 12.4.4). To develop applications with exception handling ( 12.4.5). To use the finally clause in a try-catch block ( 12.5). To use exceptions only for unexpected errors ( 12.6). To rethrow exceptions in a catch block ( 12.7). To create chained exceptions ( 12.8). To define custom exception classes ( 12.9). To discover file/directory properties, to delete and rename files/directories, and to create directories using the File class ( 12.10). To write data to a file using the PrintWriter class ( 12.11.1). To use try-with-resources to ensure that the resources are closed automatically ( 12.11.2). To read data from a file using the Scanner class ( 12.11.3). To understand how data is read using a Scanner ( 12.11.4). To develop a program that replaces text in a file ( 12.11.5). To read data from the Web ( 12.12). To develop a Web crawler ( 12.13). 4 rights reserved.

Exception Handling Exception handling enables a program to deal with exceptional situations and continue its normal execution No exception handling With if-else With a method With try-catch Quotient QuotientWithIf QuotientWithMethod QuotientWithException The benefit of using try-catch is that it enables a method to throw an exception to its caller method. Without this capability, a method must handle the exception itself or terminate the program rights reserved. 5 InputMismatchException Another way to handle similar exceptions is with the help of the InputMismatchException class Example: When executing input.nextint(), an InputMismatchException occurs if the input entered is not an int and the control is transferred to the catch block The statements in the catch block are now executed InputMismatchExceptionDemo rights reserved. 6

Exception Types Exceptions are objects based on the superclass java.lang.throwable ClassNotFoundException IOException ArithmeticException Exception NullPointerException timeexception IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes rights reserved. 7 Checked & Unchecked Exceptions Throwable Exception Error All other exceptions timeexception subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions 8

Errors caused by your program and external circumstances Throwable These rare internal system errors are thrown by JVM. If one occurs, notify the user and terminate the program Exception Error All other exceptions timeexception Caused by coding faults like bad casting, out-ofbounds array, etc. subclasses subclasses subclasses Checked Exceptions Unchecked Exceptions Program does not compile They happen only after the if any of these are present programs starts running 9 Handling Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example: o o A NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it An IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array These logic errors should be corrected in the program Unchecked exceptions can occur anywhere in the program To avoid cumbersome overuse of try-catch, Java does not mandate you to write code to catch unchecked exceptions rights reserved. 10

Declaring, Throwing and Catching Java s exception-handling model is based on three operations: 1. Declaring an exception 2. Throwing an exception 3. Catching an exception Exceptions are declared in and thrown from a method. The caller of that method can catch and handle the exception catch exception method1() { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throw exception rights reserved. 11 Declaring Exceptions Every method must state the types of checked exceptions it might throw This is known as declaring exceptions Examples: public void mymethod() throws IOException public void mymethod() throws IOException, OtherException rights reserved. 12

Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it This is known as throwing an exception Examples: throw new TheException(); TheException ex = new TheException(); throw ex; rights reserved. 13 Example: Throwing Exception /** Set a new radius */ public void setradius(double newradius) throws IllegalArgumentException { if (newradius >= 0) radius = newradius; else throw new IllegalArgumentException( "Radius cannot be negative"); rights reserved. 14

Catching Exceptions When an exception is thrown, it can be caught and handled in a try-catch block. If no exceptions arise during the execution of the try block, the catch blocks are skipped statements; // Statements that may throw exceptions catch (Exception1 exvar1) { // handler for exception1 catch (Exception2 exvar2) { // handler for exception2... catch (ExceptionN exvarn) { // handler for exceptionn If an exception is not caught in the current method, it is passed to the calling method. The process is repeated until the exception is caught or passed to main() 15 rights reserved. main method {...... invoke method1; statement1; catch (Exception1 ex1) { Process ex1; statement2; Call Stack Example: Catching Exceptions method1 {...... invoke method2; statement3; catch (Exception2 ex2) { Process ex2; statement4; method2 {...... invoke method3; statement5; catch (Exception3 ex3) { Process ex3; statement6; An exception is thrown in method3 1. If the exception type is Exception3, it is caught by the catch block for ex3 in method2. statement5 is skipped, and statement6 is executed method3 method2 method2 method1 method1 method1 main method main method main method main method 2. If the exception type is Exception2, method2 is aborted, control is returned to method1, and the exception is caught by the catch block for ex2 in method1. statement3 is skipped. statement4 is executed 3. If the exception type is Exception1, method1 is aborted, control is returned to main, and the exception is caught by the catch block for ex1 in main. statement1 is skipped. statement2 is executed 4. If the exception type is not caught in method2, method1, or main, the program terminates, and statement1 and statement2 are not executed 16 rights reserved.

Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method Example: void p2() throws IOException { if (file closed) throw new IOException("File is closed"); If p1() invokes p2() then we must write code as shown in (a) or (b) void p1() { p2(); catch (IOException ex) {... (a) void p1() throws IOException { rights reserved. p2(); (b) 17 Example: Declaring/Throwing/Catching Checked Exception This example demonstrates declaring, throwing, and catching exceptions by modifying the setradius() in the Circle class defined in Chapter 9 The new setradius() throws an exception if radius is negative CircleWithException TestCircleWithException rights reserved. 18

Rethrowing Exceptions An exception handler can rethrow the exception if the handler can t process the exception or simply wants to let its caller be notified of the exception // statements catch(theexception ex) { // perform some operations throw ex; The catch block first catches and processes the exception, and then rethrows it to the caller so that other handlers in the caller get a chance to process ex rights reserved. 19 The finally Block The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or whether an exception is caught if it occurs statements; catch(theexception ex) { finally { finalstatements; rights reserved. 20

animation Trace a Program Execution statements; catch(theexception ex) { finally { finalstatements; Next statement; Suppose no exceptions in the statements rights reserved. 21 animation Trace a Program Execution statements; catch(theexception ex) { finally { finalstatements; The final block is always executed Next statement; rights reserved. 22

animation Trace a Program Execution statements; catch(theexception ex) { finally { finalstatements; Next statement in the method is executed Next statement; rights reserved. 23 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; Suppose an exception of type Exception1 is thrown in statement2 Next statement; rights reserved. 24

animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; The exception is handled. Next statement; rights reserved. 25 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; The final block is always executed. Next statement; rights reserved. 26

animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { finally { finalstatements; The next statement in the method is now executed. Next statement; rights reserved. 27 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; statement2 throws an exception of type Exception2. Next statement; rights reserved. 28

animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; Handling exception Next statement; rights reserved. 29 animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; Execute the final block Next statement; rights reserved. 30

animation Trace a Program Execution statement1; statement2; statement3; catch(exception1 ex) { catch(exception2 ex) { throw ex; finally { finalstatements; Rethrow the exception and control is transferred to the caller Next statement; rights reserved. 31 CS 112 Programming 2 Lecture 09 Exception Handling & Text I/O (2)

First Midterm Exam Monday, 29 February (same time as the lecture) 75 minute duration Will cover all lectures delivered before the exam date Will consist of MCQ s, fill-in-the-blanks, questions with short answers, programming tasks, and drawing of diagrams If you miss this exam for any reason, you will have to appear for a makeup exam on the Thursday of the last week of teaching (5 May). That exam will cover al lectures delivered in the semester. It will consist of programming tasks, drawing of diagrams and answering questions having 0.5-1 page answers Pros & Cons of Exception Handling Advantage: Code is easier to understand and modify Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify Drawback: Slower performance, higher resource requirement Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods rights reserved. 34

When to Use Exceptions Handling? Use try-catch blocks to deal with unexpected error conditions Do not use them to deal with simple, expected situations Example: 2 nd block of code is preferable over the 1 st System.out.println(refVar.toString()); catch (NullPointerException ex) { System.out.println("refVar is null"); if (refvar!= null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); rights reserved. 35 When to Throw Exceptions? When an exception occurs in a method, if we want the exception to be processed by its caller, we should create an exception object and throw it if we can handle the exception in the method where it occurs, there is no need to throw it rights reserved. 36

Custom Exception Classes Define custom exception classes only if Java s predefined built-in classes are not sufficient Define custom exception classes by extending Exception or a subclass of Exception rights reserved. 37 Example: Custom Exception Class In Listing 12.7, setradius() throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class InvalidRadiusException CircleWithRadiusException TestCircleWithRadiusException rights reserved. 38

The File Class The File class contains the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory File is intended to provide an abstraction that deals with most of the machine-dependent complexities of files and path names in a machine-independent fashion File is a wrapper class for the filename and its directory path A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing content from/to a file rights reserved. 39 The File Class rights reserved. 40

Example: Explore File Properties Objective: Write a program that demonstrates how to create files in a platform-independent way and use the methods in the File class to obtain their properties. The following figures show a sample run of the program on Windows and on Unix. TestFileClass rights reserved. 41 Text I/O A File object does not contain the methods for reading/ writing content from/to a file In order to perform I/O, you need to create objects using appropriate Java I/O classes We can read/write strings and numeric values from/to a text file using Scanner and PrintWriter class objects rights reserved. 42

Writing Data Using PrintWriter java.io.printwriter +PrintWriter(filename: String) +print(s: String): void +print(c: char): void +print(carray: char[]): void +print(i: int): void +print(l: long): void +print(f: float): void +print(d: double): void +print(b: boolean): void Also contains the overloaded println methods. Also contains the overloaded printf methods. Creates a PrintWriter for the specified file. Writes a string. Writes a character. Writes an array of character. Writes an int value. Writes a long value. Writes a float value. Writes a double value. Writes a boolean value. A println method acts like a print method; additionally it prints a line separator. The line separator string is defined by the system. It is \r\n on Windows and \n on Unix. The printf method was introduced in 4.6, Formatting Console Output and Strings. WriteData rights reserved. 43 try-with-resources Programmers often forget to close the file. JDK 7 provides the following try-with-resources syntax that automatically closes files try (declare and create resources) { Use the resource to process the file; WriteDataWithAutoClose rights reserved. 44

Reading Data Using Scanner java.util.scanner +Scanner(source: File) +Scanner(source: String) +close() +hasnext(): boolean +next(): String +nextbyte(): byte +nextshort(): short +nextint(): int +nextlong(): long +nextfloat(): float +nextdouble(): double +usedelimiter(pattern: String): Scanner Creates a Scanner object to read data from the specified file. Creates a Scanner object to read data from the specified string. Closes this scanner. Returns true if this scanner has another token in its input. Returns next token as a string. Returns next token as a byte. Returns next token as a short. Returns next token as an int. Returns next token as a long. Returns next token as a float. Returns next token as a double. Sets this scanner s delimiting pattern. ReadData rights reserved. 45 Example: PrintWriter & Scanner Objective: Write a class named ReplaceText that replaces a string in a text file with a new string. The filename and strings are passed as command-line arguments as follows: java ReplaceText sourcefile targetfile oldstring newstring For example, invoking java ReplaceText s.txt t.txt apple orange replaces all the occurrences of apple by orange in s.txt and saves the new file in t.txt ReplaceText rights reserved. 46

Reading Data from the Web Just like we can read data from a file on your computer, we can also read data from a file on the Web rights reserved. 47 Reading Data from the Web URL url = new URL("http://google.com/index.html"); After a URL object is created, you can use openstream() defined in the URL class to open an input stream and use this stream to create a Scanner object as follows: Scanner input = new Scanner(url.openStream()); ReadFileFromURL rights reserved. 48

Case Study: Web Crawler Web Crawler: Program that traverses the Web by following URLs rights reserved. 49 Case Study: Web Crawler To ensure that each URL is traversed only once, the Web crawler maintains two lists of URLs: 1. List of URLs pending for traversing 2. List of URLs that have already been traversed Add the starting URL to a list named listofpendingurls; while!listofpendingurls.isempty() && listoftraversedurls.size()<= 100 { Remove a URL from listofpendingurls; if this URL is not in listoftraversedurls { Add it to listoftraversedurls; Display this URL; Read the page from this URL & for each URL contained in the page { Add it to listofpendingurls if it is not in listoftraversedurls; WebCrawler rights reserved. 50