Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)

Similar presentations


Presentation on theme: "CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)"— Presentation transcript:

1 CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)

2 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 2 Chapter 12 Exception Handling and Text IO

3 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 3 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

4 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 4 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).

5 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 5 Exception Handling No exception handling With a method Run Quotient Run QuotientWithIf Run QuotientWithMethod Exception handling enables a program to deal with exceptional situations and continue its normal execution With if-else Run QuotientWithException With try-catch 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

6 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 6 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 Run InputMismatchExceptionDemo

7 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 7 Exception Types Exceptions are objects based on the superclass java.lang.Throwable

8 8 Checked & Unchecked Exceptions Throwable ErrorException RuntimeException All other exceptions subclasses Checked ExceptionsUnchecked Exceptions

9 They happen only after the programs starts running Program does not compile if any of these are present 9 Errors caused by your program and external circumstances These rare internal system errors are thrown by JVM. If one occurs, notify the user and terminate the program Throwable ErrorException RuntimeException All other exceptions subclasses Checked ExceptionsUnchecked Exceptions Caused by coding faults like bad casting, out-of- bounds array, etc.

10 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 10 Handling Unchecked Exceptions  In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example: o A NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it o 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

11 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 11 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

12 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 12 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

13 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 13 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;

14 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 14 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"); }

15 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 15 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 try { 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()

16 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 16 Example: Catching Exceptions 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 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 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 4.If the exception type is not caught in method2, method1, or main, the program terminates, and statement1 and statement2 are not executed

17 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 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) 17 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

18 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 18 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 Run TestCircleWithException CircleWithException

19 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 19 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 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 try { // statements } catch(TheException ex) { // perform some operations throw ex; }

20 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 20 The finally Block try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } 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

21 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 21 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements

22 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 22 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed

23 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 23 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed

24 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 24 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2

25 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 25 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.

26 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 26 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.

27 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 27 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method is now executed.

28 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 28 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; statement2 throws an exception of type Exception2.

29 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 29 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handling exception

30 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 30 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Execute the final block

31 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 31 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Rethrow the exception and control is transferred to the caller

32 CS 112 Programming 2 Lecture 09 Exception Handling & Text I/O (2)

33 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 all lectures delivered in the semester. It will consist of programming tasks, drawing of diagrams and answering questions having 0.5-1 page answers

34 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 34 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

35 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 35 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 try { 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"); Example: 2 nd block of code is preferable over the 1 st

36 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 36 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

37 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 37 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

38 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 38 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 Run TestCircleWithRadiusException CircleWithRadiusException InvalidRadiusException

39 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 39 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

40 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 40 The File Class

41 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 41 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. Run TestFileClass

42 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 42 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

43 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 43 Writing Data Using PrintWriter Run WriteData

44 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 44 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; } Run WriteDataWithAutoClose

45 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 45 Reading Data Using Scanner Run ReadData

46 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 46 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 Run ReplaceText

47 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 47 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

48 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 48 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()); Run ReadFileFromURL

49 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 49 Case Study: Web Crawler Web Crawler: Program that traverses the Web by following URLs

50 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 50 Case Study: Web Crawler 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; } } } Run WebCrawler 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


Download ppt "CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)"

Similar presentations


Ads by Google