throw, throws and your own exception
Lesson 096 read the syntax a caller writes. This one writes the other side: a class of exception, a method that throws it, and the throws clause that makes the caller decide. An exception type of your own is worth writing when the caller can do something different about it, and when the message is not enough.
An exception of your own
InsufficientFundsException extends Exception, so it is checked, and it carries the amount that was missing as a field, so a caller can act on it without parsing a string. The withdraw method declares it, and the caller catches it:
public class Bank {
static class InsufficientFundsException extends Exception {
private static final long serialVersionUID = 1L;
private final long missing;
InsufficientFundsException(String message, long missing) {
super(message);
this.missing = missing;
}
long missing() {
return missing;
}
}
static long balance = 5000;
static void withdraw(long cents) throws InsufficientFundsException {
if (cents > balance) {
throw new InsufficientFundsException(
"cannot withdraw " + cents + " cents", cents - balance);
}
balance -= cents;
}
public static void main(String[] args) {
try {
withdraw(2000);
System.out.println("after 2000: " + balance);
withdraw(4000);
System.out.println("after 4000: " + balance);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
System.out.println("short by " + e.missing());
}
System.out.println("final: " + balance);
}
}
javac -Xlint:all Bank.java
java Bank
after 2000: 3000
cannot withdraw 4000 cents
short by 1000
final: 3000
The two failures are different in kind: the second line is a message a person reads, and the third is the number a program uses to offer a smaller amount. The balance after the failed withdrawal is 3000, which is what the last line proves: the exception left the state as it was, because the subtraction comes after the check.
The serial warning
Every exception is Serializable, and a serialisable class is expected to declare a version number. Without it, -Xlint:all says so, and the next program is left without the field so the warning appears in its real form:
Age.java:2: warning: [serial] serializable class InvalidAgeException has no definition of serialVersionUID
static class InvalidAgeException extends RuntimeException {
^
1 warning
The warning is not a mistake, but it is cheap to silence: private static final long serialVersionUID = 1L; in the class. The two programs above and below have the field and build with no output at all, and a code base that treats warnings as errors needs it.
An unchecked exception of your own
An exception that extends RuntimeException is unchecked: a caller may ignore it, and the compiler does not ask. That is right for a programming error, which no caller can recover from, and wrong for an expected condition, which the caller has to handle. The record below refuses an impossible age, and the record's constructor is the place the check belongs:
public class Age {
static class InvalidAgeException extends RuntimeException {
InvalidAgeException(String message) {
super(message);
}
}
record Person(String name, int age) {
Person {
if (age < 0 || age > 130) {
throw new InvalidAgeException("age " + age + " for " + name);
}
}
}
public static void main(String[] args) {
System.out.println(new Person("Ada", 36));
try {
new Person("Nobody", 200);
} catch (InvalidAgeException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
javac -Xlint:all Age.java
java Age
Age.java:2: warning: [serial] serializable class InvalidAgeException has no definition of serialVersionUID
static class InvalidAgeException extends RuntimeException {
^
1 warning
Person[name=Ada, age=36]
rejected: age 200 for Nobody
The choice between the two kinds is the design decision of the lesson. The bank withdrawal is a condition the caller must think about, so the exception is checked and the method signature says so. An age of 200 is a bug in the calling code, so the exception is unchecked and the constructor does not make every caller declare it.
Wrapping and the cause
A method that catches a low-level exception and throws one of its own should keep the original as the cause, so the stack trace of lesson 100 still names the line that actually failed:
public class Propagation {
static class ConfigException extends Exception {
private static final long serialVersionUID = 1L;
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int port;
static int readPort(String text) throws ConfigException {
try {
port = Integer.parseInt(text);
return port;
} catch (NumberFormatException e) {
throw new ConfigException("port is not a number: " + text, e);
}
}
public static void main(String[] args) {
for (String text : new String[] {"8080", "eighty"}) {
try {
System.out.println("port " + readPort(text));
} catch (ConfigException e) {
System.out.println(e.getMessage());
System.out.println("cause: " + e.getCause().getClass().getSimpleName());
}
}
}
}
javac -Xlint:all Propagation.java
java Propagation
port 8080
port is not a number: eighty
cause: NumberFormatException
The message names the configuration entry and the value, which is what the caller of readPort knows, and the cause is the NumberFormatException from the JDK, which is what the reader of a trace wants. A wrapper without the cause throws that away and leaves a trace that starts at the wrong line.
The call nobody handles
A method that declares a checked exception must be called from a place that handles it or declares it too. The compiler reports the call, not the declaration:
public class Unhandled {
static void risky() throws java.io.IOException {
}
public static void main(String[] args) {
risky();
System.out.println("done");
}
}
javac -Xlint:all Unhandled.java
Unhandled.java:6: error: unreported exception IOException; must be caught or declared to be thrown
risky();
^
1 error
The two ways out are the two halves of the check: wrap the call in a try, or add throws java.io.IOException to main and let the JVM print the trace. The second is the shorter and the worse for a program that a person runs, because the trace is the only report; a library does it, and an application handles the exception where it can say what failed.
Exercises
- Give InsufficientFundsException a second field for the balance and print it in the catch.
- Make withdraw return the new balance and throw when the amount is not positive as well.
- Add the serialVersionUID to Age and confirm the build is silent.
- Catch ConfigException in readPort and rethrow it with an English message, keeping the cause.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
throwson a method declare?Answer
The checked exceptions the method may pass to its caller
The clause is part of the signature, so every caller knows what it must handle.
-
When is an exception of your own unchecked?
Answer
When it extends RuntimeException
The two branches of Exception decide whether the compiler tracks the type.
-
Why pass the original exception as the cause?
Answer
The stack trace still names the line that failed
The cause keeps the lower-level failure visible under the higher-level message.
-
What does this program print?
public class Q1 { static class Small extends RuntimeException { Small(String message) { super(message); } } public static void main(String[] args) { try { throw new Small("too small"); } catch (Small e) { System.out.println(e.getMessage()); } } }Answer
too small
The message goes to the superclass constructor and getMessage returns it.
-
Why is an exception of your own better than one message string?
Answer
It carries fields the caller can use and a type the caller can catch
The missing amount is data, and a separate type lets the caller tell this failure from others.
-
What must a caller of a method that throws a checked exception do?
Answer
Catch it, or declare it on its own signature
The compiler follows the throws clause up the call chain until someone handles it.
-
What does the serial warning ask for?
Answer
A serialVersionUID field in the exception class
Every exception is Serializable, and the field is the version of that form.
-
What does this program print?
public class Q2 { static class E extends Exception { E(String message) { super(message); } } static void fail() throws E { throw new E("failed"); } public static void main(String[] args) { try { fail(); } catch (E e) { System.out.println("caught " + e.getMessage()); } } }Answer
caught failed
The checked exception crosses one call and is caught in main, which prints the message.
-
What does this program print?
public class Q3 { record P(int v) { P { if (v > 10) { throw new IllegalArgumentException("too big: " + v); } } } public static void main(String[] args) { try { new P(20); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } }Answer
too big: 20
The compact constructor refuses the value and the message names it.
-
What is the first line of the compiler output for this program?
public class Q4 { static void fail() throws java.io.IOException { } public static void main(String[] args) { fail(); } }Answer
error: unreported exception IOException; must be caught or declared to be thrown
The caller neither catches the checked exception nor declares it.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev