Exception Handling and Text I/O in Java

Exception Handling and Text I/O

Motivations

  • Runtime errors cause abnormal program termination.

  • Exception handling allows programs to continue running or terminate gracefully when runtime errors occur.

Objectives

  • Overview of exceptions and exception handling (§12.2).

  • Explore advantages of using exception handling (§12.2).

  • Distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked (§12.3).

  • Declare exceptions in a method header (§12.4.1).

  • Throw exceptions in a method (§12.4.2).

  • Write a try-catch block to handle exceptions (§12.4.3).

  • Explain how an exception is propagated (§12.4.3).

  • Obtain information from an exception object (§12.4.4).

  • Develop applications with exception handling (§12.4.5).

  • Use the finally clause in a try-catch block (§12.5).

  • Use exceptions only for unexpected errors (§12.6).

  • Rethrow exceptions in a catch block (§12.7).

  • Create chained exceptions (§12.8).

  • Define custom exception classes (§12.9).

  • Discover file/directory properties, to delete and rename files/directories, and to create directories using the File class (§12.10).

  • Write data to a file using the PrintWriter class (§12.11.1).

  • Use try-with-resources to ensure that the resources are closed automatically (§12.11.2).

  • Read data from a file using the Scanner class (§12.11.3).

  • Understand how data is read using a Scanner (§12.11.4).

  • Develop a program that replaces text in a file (§12.11.5).

  • Read data from the Web (§12.12).

  • Develop a Web crawler (§12.13).

Exception-Handling Overview

  • Runtime errors can be fixed using if statements or with methods like QuotientWithIf and QuotientWithMethod.

Exception Advantages

  • Exception handling allows a method to throw an exception to its caller.

  • Without exception handling, a method must handle the exception or terminate the program.

  • Example: QuotientWithException

Handling InputMismatchException

  • InputMismatchException handling allows a program to continuously read input until it is correct.

  • Example: InputMismatchExceptionDemo

Exception Types

  • Exceptions are categorized into Error and Exception types.

System Errors

  • System errors are thrown by the JVM and represented by the Error class.

  • Error class describes internal system errors that rarely occur.

  • Handling system errors typically involves notifying the user and attempting graceful termination.

Exceptions

  • Exceptions are caused by program errors or external circumstances.

  • Exceptions can be caught and handled by the program.

Runtime Exceptions

  • RuntimeException is caused by programming errors.

  • Examples include bad casting, out-of-bounds array access, and numeric errors.

Checked Exceptions vs. Unchecked Exceptions

  • RuntimeException, Error, and their subclasses are unchecked exceptions.

  • All other exceptions are checked exceptions.

  • The compiler forces the programmer to check and handle checked exceptions.

Unchecked Exceptions

  • Unchecked exceptions often reflect non-recoverable programming logic errors.

  • Examples: NullPointerException, IndexOutOfBoundsException.

  • Java does not mandate catching unchecked exceptions to avoid overuse of try-catch blocks.

Declaring, Throwing, and Catching Exceptions

Declaring Exceptions
  • Methods must declare the checked exceptions they might throw.

  • Syntax:
    public void myMethod() throws IOExceptionpublic\ void\ myMethod()\ throws\ IOException
    public void myMethod() throws IOException, OtherExceptionpublic\ void\ myMethod()\ throws\ IOException,\ OtherException

Throwing Exceptions
  • The program creates an instance of an exception type and throws it when an error is detected.

  • Examples:
    throw new TheException();throw\ new\ TheException();
    TheException ex = new TheException();TheException\ ex\ =\ new\ TheException();
    throw ex;throw\ ex;

  • Example:

    public void setRadius(double newRadius)
    throws IllegalArgumentException {
        if (newRadius >= 0)
            radius = newRadius;
        else
            throw new IllegalArgumentException("Radius cannot be negative");
    }
    
Catching Exceptions
  • Syntax:

    try {
        statements; // Statements that may throw exceptions
    } catch (Exception1 exVar1) {
        handler for exception1;
    } catch (Exception2 exVar2) {
        handler for exception2;
    } ... catch (ExceptionN exVar3) {
        handler for exceptionN;
    }
    

Catch or Declare Checked Exceptions

  • Java requires dealing with checked exceptions.

  • Checked exceptions (excluding Error or RuntimeException) must be handled in a try-catch block or declared to be thrown by the calling method.

  • If method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), p1 must either catch the exception or declare that it throws the exception.

Example: Declaring, Throwing, and Catching Exceptions

  • Objective: Demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method in the Circle class.

  • The setRadius method throws an exception if the radius is negative.

  • Files: TestCircleWithException, CircleWithException.

Rethrowing Exceptions

  • Syntax:
    java try { statements; } catch(TheException ex) { perform operations before exits; throw ex; }

The finally Clause

  • Syntax:
    java try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }

  • The finally block is always executed, regardless of whether an exception is thrown or caught.

Trace a Program Execution

  • If no exceptions are thrown in the try block:

    • Statements in the try block are executed.

    • The finally block is executed.

    • The next statement after the finally block is executed.

  • If an exception is thrown in the try block and caught by a catch block:

    • The corresponding catch block is executed.

    • The finally block is executed.

    • The next statement after the finally block is executed.

  • If an exception is thrown in the try block and re-thrown in a catch block:

    • The corresponding catch block is executed.

    • The finally block is executed.

    • The exception is re-thrown and control is transferred to the caller.

Cautions When Using Exceptions

  • Exception handling separates error-handling code from normal programming tasks.

  • Exception handling requires more time and resources due to the instantiation of a new exception object, stack rollback, and error propagation.

When to Throw Exceptions

  • If an exception occurs in a method and you want it to be processed by the caller, create and throw an exception object.

  • If the exception can be handled in the method where it occurs, there is no need to throw it.

When to Use Exceptions

  • Use try-catch blocks for unexpected error conditions, not for simple, expected situations.

  • Example: Instead of catching NullPointerException, check if the reference variable is null using an if statement.

Defining Custom Exception Classes

  • Use predefined exception classes in the API whenever possible.

  • Define custom exception classes if the predefined classes are not sufficient.

  • Custom exception classes should extend Exception or a subclass of Exception.

Custom Exception Class Example

  • If you want to pass the radius to the handler when the setRadius method throws an exception, create a custom exception class.

  • Files: TestCircleWithRadiusException, CircleWithRadiusException, InvalidRadiusException.

Assertions

  • Assertions are Java statements that enable you to assert assumptions about your program.

  • An assertion contains a Boolean expression that should be true during program execution.

  • Assertions assure program correctness and help avoid logic errors.

Declaring Assertions

  • Declared using the assert keyword:
    assert assertion;assert\ assertion;
    assert assertion : detailMessage;assert\ assertion\ :\ detailMessage;

  • assertion is a Boolean expression, and detailMessage is a primitive-type or an Object value.

Executing Assertions

  • When an assertion statement is executed, Java evaluates the assertion.

  • If it is false, an AssertionError will be thrown.

  • AssertionError is a subclass of Error. When an assertion fails, the program displays a message and exits.

Executing Assertions Example

public class AssertionDemo {
    public static void main(String[] args) {
        int i; int sum = 0;
        for (i = 0; i < 10; i++) {
            sum += i;
        }
        assert i == 10;
        assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
    }
}

Compiling Programs with Assertions

  • Use a JDK 1.4 compiler or later.

  • Include the -source 1.4 switch in the compiler command for JDK 1.4:
    javac source 1.4 AssertionDemo.javajavac\ -source\ 1.4\ AssertionDemo.java

  • JDK 1.5 and later do not require the -source 1.4 option.

Running Programs with Assertions

  • Assertions are disabled by default at runtime.

  • Enable assertions using the -enableassertions or -ea switch:
    java ea AssertionDemojava\ -ea\ AssertionDemo

  • Assertions can be selectively enabled/disabled at the class or package level.

  • Disable switch: -disableassertions or -da.

  • Example: Enable assertions in package1 and disable assertions in Class1:
    java ea:package1 da:Class1 AssertionDemojava\ -ea:package1\ -da:Class1\ AssertionDemo

Using Exception Handling or Assertions

  • Assertions should not replace exception handling.

  • Exception handling deals with unusual circumstances, while assertions ensure program correctness.

  • Exception handling addresses robustness, and assertions address correctness.

  • Assertions are for internal consistency and validity checks, not normal tests.

  • Assertions are checked at runtime and can be turned on or off.

Using Exception Handling or Assertions (cont.)

  • Do not use assertions for argument checking in public methods.

  • Valid arguments for public methods are part of the method's contract and must be obeyed whether assertions are enabled or disabled.

  • Example: Use exception handling instead of assertions for argument checking in the setRadius method.

Using Exception Handling or Assertions (cont.)

  • Use assertions to reaffirm assumptions and increase confidence in program correctness.

  • Replace assumptions with assertions in the code.

Using Exception Handling or Assertions (cont.)

  • Place assertions in a switch statement without a default case.

    switch (month) {
        case 1: ... ; break;
        case 2: ... ; break;
        ...  case 12: ... ; break;
        default: assert false : "Invalid month: " + month;
    }
    

The File Class

  • The File class provides an abstraction for handling machine-dependent complexities of files and path names.

  • The filename is a string.

  • The File class is a wrapper class for the file name and its directory path.

Obtaining file properties and manipulating files

  • Methods in the File class allow you to obtain file properties and perform file manipulations.

Problem: Explore File Properties

  • Objective: Demonstrate how to create files in a platform-independent way and use methods in the File class to obtain their properties.

  • Example: TestFileClass.

Text I/O

  • A File object encapsulates file properties but does not contain methods for reading/writing data.

  • Use Java I/O classes (e.g., Scanner, PrintWriter) to read/write data from/to a file.

Writing Data Using PrintWriter

  • Example: WriteData.

Try-with-resources

  • JDK 7 provides the try-with-resources syntax for automatically closing files.

  • Syntax:
    java try (declare and create resources) { Use the resource to process the file; }

  • Example: WriteDataWithAutoClose.

Reading Data Using Scanner

  • Example: ReadData.

Problem: Replacing Text

  • Write a class named ReplaceText that replaces a string in a text file with a new string.

  • Command-line arguments:
    java ReplaceText sourceFile targetFile oldString newStringjava\ ReplaceText\ sourceFile\ targetFile\ oldString\ newString

  • Example: java ReplaceText FormatString.java t.txt StringBuilder StringBuffer

  • File: ReplaceText

Reading Data from the Web

  • Read data from a file on the Web.

Reading Data from the Web

  • Create a URL object:
    URL url = new URL("www.google.com/index.html");URL\ url\ =\ new\ URL("www.google.com/index.html");

  • Use the openStream() method to open an input stream and create a Scanner object:
    Scanner input = new Scanner(url.openStream());Scanner\ input\ =\ new\ Scanner(url.openStream());

  • Example: ReadFileFromURL

Case Study: Web Crawler

  • Develop a program that traverses the Web by following hyperlinks.

Case Study: Web Crawler

  • The program follows URLs to traverse the Web, avoiding duplicate visits.

  • It maintains two lists of URLs: pending and traversed.

Case Study: Web Crawler

  • Algorithm:

    1. Add the starting URL to listOfPendingURLs.

    2. While listOfPendingURLs is not empty:

      • Remove a URL from listOfPendingURLs.

      • If this URL is not in listOfTraversedURLs:

        • Add it to listOfTraversedURLs.

        • Display this URL.

        • Exit the loop when the size of the traversed URLs is equal to 100.

        • Read the page from this URL and for each URL contained in the page:

          • Add it to listOfPendingURLs if it is not in listOfTraversedURLs.

  • File : WebCrawler