Sub topic 7
Throwing and Declaring Exceptions
So far you have caught exceptions that Java threw for you. Your own code can also throw exceptions. You do this when a method gets input it cannot work with, or when it hits a problem it cannot fix by itself.
Java uses two keywords for this, and their names are almost the same:
throwis a statement that creates a failure right now.throwsis part of a method's header. It warns callers that the method might fail with a certain exception.
Throwing an Exception with `throw`
To throw an exception, you create an exception object with new and pass it to throw. The method stops at that line. Java then looks for a matching catch block in the method that called it.
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("Error: " + e.getMessage());
}
}
}Output:
Age set to 30
Error: age cannot be negative: -5IllegalArgumentException is an unchecked exception, so setAge does not have to declare it. The message you pass to the constructor comes back later from getMessage().
Declaring an Exception with `throws`
Checked exceptions, such as IOException, follow a stricter rule. If your method can throw one, you have two choices. You can catch it inside the method, or you can declare it with throws after the parameter list.
import java.io.IOException;
public class ConfigLoader {
static String load(String name) throws IOException {
if (name.isEmpty()) {
throw new IOException("no file name given");
}
return "settings from " + name;
}
public static void main(String[] args) {
try {
System.out.println(load("app.cfg"));
System.out.println(load(""));
} catch (IOException e) {
System.out.println("Could not load: " + e.getMessage());
}
}
}Output:
settings from app.cfg
Could not load: no file name givenIf you delete throws IOException from load, the program will not compile. The compiler reports unreported exception IOException; must be caught or declared to be thrown.
The caller now has the same choice. main catches the exception here. It could also pass it on by writing public static void main(String[] args) throws IOException.
`throw` vs `throws` at a Glance
| Keyword | Where it goes | What it does |
|---|---|---|
| `throw` | Inside a method body | Throws one exception object right away |
| `throws` | In the method header | Lists the checked exceptions the method may pass to its caller |
Exercise
Write a method static int checkPercent(int p) that returns p if it is between 0 and 100, and otherwise throws an IllegalArgumentException. Does the method header need a throws clause?
Show answer
static int checkPercent(int p) { if (p < 0 || p > 100) { throw new IllegalArgumentException("percent out of range: " + p); } return p; } The header does not need a throws clause, because IllegalArgumentException is unchecked.
Exercise
A method contains throw new IOException("disk full"); but its header has no throws clause and no surrounding try/catch. What happens, and what are the two ways to fix it?
Show answer
The code does not compile, because IOException is a checked exception. One fix is to add throws IOException to the method header. The other fix is to wrap the throw in a try block with a matching catch (IOException e) block.