Lecture 5: Exception
Handling and Text File I/O
Michael Hsu
CSULA
What Is an Exception
Exception is an event where something
abnormal happens.
When an error occurs within a method, the
method creates an exception object with
various information about the event. We
call this throwing an exception.
The call stack refers to the ordered list of
methods called when you get to where the
exception occurred.
What Is an Exception Cont.
You can handle the exception by
creating a handler that matches
that specific type.
For example, catching an
FileNotFoundException
This is called catching the
exception
If the exception is not caught, the
program is terminated.
Types of Exceptions
There are three main types of exceptions
Checked Exceptions
Errors
Runtime Exceptions
Exception Types
ClassNotFoundException
ArithmeticException
IOException
Exception
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object
IllegalArgumentException
Throwable
Many more classes
LinkageError
Error
VirtualMachineError
Many more classes
5
System Errors
ClassNotFoundException
ArithmeticException
IOException
Exception
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
6
IllegalArgumentException
Throwable
Many more classes
LinkageError
Error
VirtualMachineError
Many more classes
Exceptions
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
ClassNotFoundException
ArithmeticException
IOException
Exception
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object
IllegalArgumentException
Throwable
Many more classes
LinkageError
Error
VirtualMachineError
Many more classes
7
Runtime Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object
IllegalArgumentException
Throwable
Many more classes
LinkageError
Error
VirtualMachineError
Many more classes
8
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
Checked Exceptions vs. Unchecked
Exceptions
RuntimeException, Error and their subclasses are known as unchecked
exceptions.
All other exceptions are known as checked exceptions, meaning that the
compiler forces the programmer to check and deal with the exceptions.
9
Unchecked Exceptions
In most cases, unchecked exceptions reflect programming logic errors that
are not recoverable.
For example, 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 are the logic errors that should be corrected in the program.
Unchecked exceptions can occur anywhere in the program.
To avoid cumbersome overuse of try-catch blocks, Java does not mandate you
to write code to catch unchecked exceptions.
10
Unchecked Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception
NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object
IllegalArgumentException
Throwable
Many more classes
LinkageError
Error
VirtualMachineError
Many more classes
11
Unchecked
exception.
Declaring, Throwing, and Catching
Exceptions
method1() {
try {
invoke method2;
}
catch (Exception ex) {
Process exception;
}
catch exception
}
12
declare exception
method2() throws Exception {
if (an error occurs) {
throw new Exception();
}
}
throw exception
Declaring Exceptions
Every method must state the types of checked exceptions it might throw.
This is known as declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
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. Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
14
Throwing Exceptions Example
/** 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
Catching Exceptions
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;
}
16
Catching Exceptions
try
try
try
catch
catch
catch
An exception
is thrown in
method3
Call Stack
method3
main method
17
method2
method2
method1
method1
method1
main method
main method
main method
Catch or Declare Checked Exceptions
Suppose p2 is defined as follows:
void p2() throws IOException {
if (a file does not exist) {
throw new IOException("File does not exist");
}
...
}
18
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method
declares a checked exception (i.e., an exception other than Error
or RuntimeException), you must invoke it in a try-catch block or
declare to throw the exception in the calling method. For example,
suppose that method p1 invokes method p2 and p2 may throw a
checked exception (e.g., IOException), you have to write the code
as shown in (a) or (b).
void p1() {
try {
p2();
}
catch (IOException ex) {
...
}
}
(a)
19
void p1() throws IOException {
p2();
}
(b)
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
20
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
21
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
22
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
23
The final block is
always executed
Trace a Program Execution
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
24
Next statement in the
method is executed
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
25
Suppose an exception
of type Exception1 is
thrown in statement2
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
26
The exception is
handled.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
27
The final block is
always executed.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
28
The next statement in
the method is now
executed.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
29
statement2 throws an
exception of type
Exception2.
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
30
Handling exception
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
31
Execute the final block
Trace a Program Execution
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
32
Rethrow the exception
and control is
transferred to the caller
Cautions When Using Exceptions
33
Exception handling separates error-handling code from normal programming
tasks, thus making programs easier to read and to modify.
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.
When to Throw Exceptions
34
An exception occurs in a method. If you want the exception to be processed
by its caller, you should create an exception object and throw it. If you can
handle the exception in the method where it occurs, there is no need to
throw it.
When to Use Exceptions
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
35
}
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
36
Text File I/O
Heavily Borrowed from
https://docs.oracle.com/javase/tutorial/essential/io/
Basic Concepts: Path
Most operating systems have file directories (folders on your computer), and
you can refer to a file by its path.
For example: C:\Pikachu\Moves\thunderbolt.txt
Difference between relative paths and absolute paths
A path is either relative or absolute.
An absolute path always contains the root element and the complete directory list
required to locate the file.
Absolute path: C:\Pikachu\Moves\thunderbolt.txt
Relative path: Moves\thunderbolt.txt
The Path Class
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html
An Interface (to be discusses next week)
It is a programmatic representation of a path in the file system
Contains file name, directory list
It allows you to modify, check directories/folders/etc, and access files
through it.
Creating a Path:
//Microsoft windows
Path path = Paths.get("C:\\Users\\Pikachu\\Documents");
//Shorthand for FileSystems.getDefault().getPath(…)
Try-with-resources
File I/O operations use up system resources. Just like
Scanners you used before, you have to close them.
Programmers often forget to close their resources. try-withresources syntax that automatically closes the resources.
try (declare and create resources) {
Use the resource to process the file;
}
40
Text File Manipulation:
Checking if the File Exists
Checking if it exsists
//Verify that the file exists
Path path = Paths.get("C:\\Users\\Pickachu\\Documents");
System.out.println(Files.exists(path));
Note: If both exists and notExists return false, the existence of the file cannot
be verified.
Text File Manipulation:
Deleting a File
Path path = Paths.get("C:\\Users\\Pickachu\\Documents");
try {
Files.delete(path);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n",
path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
Text File Manipulation:
Reading a File Line By Line
Path path = Paths.get("C:\\Users\\Pickachu\\Documents");
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(path, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Text File Manipulation:
Reading All Lines from a File
Charset charset = Charset.forName("US-ASCII");
List<String> allLinesInFile = new ArrayList<String>();
try (BufferedReader reader = Files.newBufferedReader(path,
charset)) {
allLinesInFile = Files.readAllLines(path, charset);
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Text File Manipulation:
Write to a File
Charset charset = Charset.forName("US-ASCII");
String s = "hahaha";
//This opens or creates an existing file
try (BufferedWriter writer = Files.newBufferedWriter(path,
charset)) {
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
Example: Writing Classroom
Information to File
© Copyright 2025 Paperzz