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
ifstatements or with methods likeQuotientWithIfandQuotientWithMethod.
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
InputMismatchExceptionhandling allows a program to continuously read input until it is correct.Example:
InputMismatchExceptionDemo
Exception Types
Exceptions are categorized into
ErrorandExceptiontypes.
System Errors
System errors are thrown by the JVM and represented by the
Errorclass.Errorclass 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
RuntimeExceptionis 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-catchblocks.
Declaring, Throwing, and Catching Exceptions
Declaring Exceptions
Methods must declare the checked exceptions they might throw.
Syntax:
Throwing Exceptions
The program creates an instance of an exception type and throws it when an error is detected.
Examples:
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
ErrororRuntimeException) must be handled in atry-catchblock or declared to be thrown by the calling method.If method
p1invokes methodp2andp2may throw a checked exception (e.g.,IOException),p1must 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
setRadiusmethod in theCircleclass.The
setRadiusmethod 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
finallyblock is always executed, regardless of whether an exception is thrown or caught.
Trace a Program Execution
If no exceptions are thrown in the
tryblock:Statements in the
tryblock are executed.The
finallyblock is executed.The next statement after the
finallyblock is executed.
If an exception is thrown in the
tryblock and caught by acatchblock:The corresponding
catchblock is executed.The
finallyblock is executed.The next statement after the
finallyblock is executed.
If an exception is thrown in the
tryblock and re-thrown in acatchblock:The corresponding
catchblock is executed.The
finallyblock 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-catchblocks for unexpected error conditions, not for simple, expected situations.Example: Instead of catching
NullPointerException, check if the reference variable isnullusing anifstatement.
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
Exceptionor a subclass ofException.
Custom Exception Class Example
If you want to pass the radius to the handler when the
setRadiusmethod 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
assertkeyword:assertionis a Boolean expression, anddetailMessageis a primitive-type or anObjectvalue.
Executing Assertions
When an assertion statement is executed, Java evaluates the assertion.
If it is false, an
AssertionErrorwill be thrown.AssertionErroris a subclass ofError. 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.4switch in the compiler command for JDK 1.4:JDK 1.5 and later do not require the
-source 1.4option.
Running Programs with Assertions
Assertions are disabled by default at runtime.
Enable assertions using the
-enableassertionsor-easwitch:Assertions can be selectively enabled/disabled at the class or package level.
Disable switch:
-disableassertionsor-da.Example: Enable assertions in
package1and disable assertions inClass1:
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
setRadiusmethod.
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
switchstatement without adefaultcase.switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : "Invalid month: " + month; }
The File Class
The
Fileclass provides an abstraction for handling machine-dependent complexities of files and path names.The filename is a string.
The
Fileclass is a wrapper class for the file name and its directory path.
Obtaining file properties and manipulating files
Methods in the
Fileclass 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
Fileclass to obtain their properties.Example:
TestFileClass.
Text I/O
A
Fileobject 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-resourcessyntax 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
ReplaceTextthat replaces a string in a text file with a new string.Command-line arguments:
Example:
java ReplaceText FormatString.java t.txt StringBuilder StringBufferFile:
ReplaceText
Reading Data from the Web
Read data from a file on the Web.
Reading Data from the Web
Create a
URLobject:Use the
openStream()method to open an input stream and create aScannerobject: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:
Add the starting URL to
listOfPendingURLs.While
listOfPendingURLsis 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
listOfPendingURLsif it is not inlistOfTraversedURLs.
File :
WebCrawler