Sub topic 7
Throwing and Declaring Exceptions
So far you have caught exceptions that Java threw for you. In this chapter, your own code throws them. You will learn two keywords that look alike but do different jobs:
throwis a statement. It creates a problem report and sends it up the call chain right now.throwsis part of a method's header. It warns callers that the method might send out a certain kind of exception.
Why Throw an Exception Yourself?
Sometimes a method gets input it cannot work with. Suppose a method sets a person's age and someone passes -5. The method could print a warning and carry on, but then the program holds bad data. It could return a special value like -1, but callers can forget to check for it.
Throwing an exception is the clearer choice. It stops the method at once. It also forces the problem to be dealt with somewhere, because nobody can accidentally ignore it.
The throw Statement
The throw statement takes one exception object. You usually create that object with new on the same line.
public class AgeCheck {
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("age cannot be negative: " + age);
}
System.out.println("Age set to " + age);
}
public static void main(String[] args) {
setAge(30);
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
}
System.out.println("Done");
}
}Output:
Age set to 30
Caught: age cannot be negative: -5
DoneHere is what happens on the second call:
setAge(-5)checks the value and finds it is negative.throwsends the exception out. The lineSystem.out.println("Age set to " + age);never runs.- Java looks for a matching
catchblock, first insetAge, then in its caller. It finds one inmain. - The
catchblock runs, and the program continues after it.
IllegalArgumentException is a built-in unchecked exception. It means "the caller gave me a bad argument." The text you pass to the constructor becomes the message, and getMessage() returns it.
Useful Built-in Exceptions to Throw
You do not need to invent a new class for every problem. Java already has exceptions for common cases.
| Exception | Checked? | Throw it when |
|---|---|---|
| `IllegalArgumentException` | No | A method argument has a bad value |
| `IllegalStateException` | No | The object is not ready for this call, such as reading from a closed connection |
| `NullPointerException` | No | A required argument is `null` |
| `UnsupportedOperationException` | No | The method is not supported by this object |
| `IOException` | Yes | Reading or writing data failed |
The throws Clause
Recall from the earlier chapter that checked exceptions are ones the compiler tracks. For these, Java has a rule called handle or declare. A method that might let a checked exception escape must do one of two things:
- Handle it with
tryandcatch. - Declare it with a
throwsclause in the method header.
A throws clause is the word throws followed by one or more exception types, written after the parameter list.
import java.io.IOException;
public class ConfigLoader {
static String loadSetting(String name) throws IOException {
if (name.isEmpty()) {
throw new IOException("setting name is empty");
}
return "value-of-" + name;
}
static void printSetting(String name) throws IOException {
System.out.println(loadSetting(name));
}
public static void main(String[] args) {
try {
printSetting("color");
printSetting("");
} catch (IOException e) {
System.out.println("Could not load: " + e.getMessage());
}
}
}Output:
value-of-color
Could not load: setting name is emptyLook at how the duty moves up the call chain:
loadSettingthrows anIOException, so it declaresthrows IOException.printSettingcallsloadSettingbut does not catch the exception. It must declarethrows IOExceptiontoo.maincatches it, somainneeds nothrowsclause.
What the Compiler Says If You Forget
If you remove throws IOException from printSetting, the program will not compile. javac reports something like this:
ConfigLoader.java:12: error: unreported exception IOException; must be caught or declared to be thrown
System.out.println(loadSetting(name));
^This error is a feature. The compiler makes sure no checked exception slips by unnoticed.
Declaring Several Exceptions
Separate several types with commas:
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Downloader {
static String download(String url) throws IOException, TimeoutException {
if (url.startsWith("slow:")) {
throw new TimeoutException("server took too long");
}
if (!url.startsWith("http")) {
throw new IOException("unsupported address: " + url);
}
return "content of " + url;
}
public static void main(String[] args) {
String[] urls = {"https://example.com", "ftp://old.site", "slow:server"};
for (String url : urls) {
try {
System.out.println(download(url));
} catch (IOException | TimeoutException e) {
System.out.println("Failed: " + e.getMessage());
}
}
}
}Output:
content of https://example.com
Failed: unsupported address: ftp://old.site
Failed: server took too longUnchecked Exceptions and throws
You may list unchecked exceptions in a throws clause, but the compiler does not require it. Some programmers list them anyway as documentation. A more common habit is to describe them in the method's Javadoc comment with @throws.
Edge Cases to Know
Code After throw Cannot Run
A throw always leaves the current block. If you put a statement directly after it in the same block, the compiler rejects it with an "unreachable statement" error.
public class Unreachable {
static int check(int x) {
if (x < 0) {
throw new IllegalArgumentException("negative");
// x = 0; // uncommenting this line causes: unreachable statement
}
return x;
}
public static void main(String[] args) {
System.out.println(check(7));
}
}This also means a method that ends with throw does not need a return after it.
Throwing null
throw null; compiles, but at run time Java throws a NullPointerException instead. Always throw a real object.
Rethrowing from a catch Block
A catch block can do some work, such as logging, and then throw the same exception again so a caller can handle it.
import java.io.IOException;
public class Rethrow {
static void save() throws IOException {
try {
throw new IOException("disk full");
} catch (IOException e) {
System.out.println("Logging: " + e.getMessage());
throw e;
}
}
public static void main(String[] args) {
try {
save();
} catch (IOException e) {
System.out.println("main handled: " + e.getMessage());
}
}
}Because the exception leaves save again, save still needs throws IOException.
main Can Declare throws
public static void main(String[] args) throws IOException is legal. If an exception escapes main, the program stops and prints a stack trace. This is fine for small experiments, but real programs should handle problems properly.
Overriding Methods
When a subclass overrides a method, the new version cannot declare broader or extra checked exceptions than the original. It may declare fewer, narrower ones, or none at all.
| Parent method declares | Overriding method may declare |
|---|---|
| `throws IOException` | `throws IOException`, a subclass of it such as `FileNotFoundException`, or nothing |
| `throws IOException` | Not `throws Exception`, because that is broader |
| nothing | No checked exceptions at all (unchecked ones are always allowed) |
This rule protects callers. Code written against the parent method only expects the exceptions the parent lists.
Summary
throwsends one exception object out of the current method right away.throwsin a method header lists the checked exceptions that may escape.- Checked exceptions follow the handle-or-declare rule. Unchecked exceptions do not.
- Prefer a fitting built-in exception, and write a clear message.
Exercise
Write a method static double squareRoot(double x) that throws an IllegalArgumentException with the message "x must not be negative: " plus the value when x is less than 0, and otherwise returns Math.sqrt(x). Does it need a throws clause?
Show answer
static double squareRoot(double x) { if (x < 0) { throw new IllegalArgumentException("x must not be negative: " + x); } return Math.sqrt(x); } It needs no throws clause, because IllegalArgumentException is unchecked.
Exercise
Method a() calls method b(), and b() declares throws IOException. Method a() has no try/catch and no throws clause. What happens, and what are two ways to fix it?
Show answer
The program does not compile, with the error "unreported exception IOException; must be caught or declared to be thrown". Fix it by wrapping the call to b() in try/catch (IOException e) inside a(), or by adding throws IOException to a()'s header.
Exercise
A parent class has the method void load() throws IOException. Which of these overriding headers compile: (1) void load(), (2) void load() throws FileNotFoundException, (3) void load() throws Exception?
Show answer
(1) and (2) compile. Declaring nothing, or a narrower subclass of IOException, is allowed. (3) does not compile, because Exception is broader than IOException.