Sub topic 10
Handle and Declare Exceptions
An exception is a signal that something went wrong while a program was running. For example, a method that reads a file may not find it. Instead of returning a normal result, the method can signal the problem to the code that called it.
A method’s contract is what its callers can expect from it, including possible failures. Java lets a method declare some exceptions as part of that contract.
Read a file safely
This example uses Java 11 or later. Create a file named message.txt containing Hello, Java!. Save the following code as ReadMessage.java in the same folder.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
class ReadMessage {
static String readMessage(String fileName) throws IOException {
String text = Files.readString(Paths.get(fileName));
if (text.isEmpty()) {
throw new IOException("The file is empty");
}
return text;
}
public static void main(String[] args) {
try {
String message = readMessage("message.txt");
System.out.println(message);
} catch (IOException error) {
System.out.println("Could not read the message: "
+ error.getMessage());
}
}
}The import lines let the code use types from Java’s built-in library. Files.readString reads the text in the named file. IOException is a type of exception for input or output problems, such as a file that cannot be read.
In a terminal, go to the folder with both files and run:
javac ReadMessage.java
java ReadMessageThe program prints Hello, Java!. Now rename or remove message.txt and run the second command again. The program prints a message saying it could not read the file. The exact details can vary by system.
Declare and throw an exception
Look at the readMessage declaration:
throws IOExceptionsays that the method may pass anIOExceptionto its caller.throw new IOException(...)creates and throws an exception when the file is empty.
Throwing an exception stops the method’s normal work. It does not reach return text. The exception is passed back to the caller unless it is handled in the method.
The two words have different jobs: throws appears in a method declaration; throw raises an exception at a particular point in the code.
Catch an exception
The caller is the code that calls a method. In the example, main calls readMessage.
A try block holds code that may cause an exception. A catch block handles an exception of the named type. If reading fails, Java skips the remaining statements in the try block and runs the matching catch block.
In the catch block, error is a variable holding the exception. error.getMessage() gets a description of the problem. If reading succeeds, Java skips the catch block.
Handling an exception should give the caller or user a useful response. Avoid catching an exception and silently ignoring it: that can hide a problem.
Know which exceptions to declare
The Java compiler is the tool that checks and translates Java code before it runs. For a checked exception, the compiler requires a method either to catch it or to declare it with throws.
IOException is checked. That is why readMessage declares it, while main catches it.
An unchecked exception does not have that compiler requirement. For example, IllegalArgumentException can signal that a caller supplied an unsuitable value. It can still be caught, but it does not have to be declared.
If no matching handler catches an exception as it passes back through callers, the program can stop and show an error. Declaring throws alone does not prevent that.
Practice
Exercise
What happens if message.txt is empty in the example?
Show answer
readMessage throws an IOException. The catch block in main handles it and prints a message that includes “The file is empty”.
Exercise
If a method calls readMessage without catching IOException, what must it do to compile?
Show answer
It must declare IOException with throws, so the exception can be passed to its caller.