Exceptions: checked, unchecked and try-with-resources
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
What an exception is
When something goes wrong at runtime, such as a missing file, text that is not a number or a call on null, Java creates an exception object and throws it. The method stops, and the exception travels up the call stack until some code catches it. If nothing catches it, the program ends and prints a stack trace.
Two families
All exceptions descend from Throwable. The two branches below it matter most.
- Checked exceptions extend
Exceptionbut notRuntimeException. The compiler forces you to either catch them or declare them withthrows.IOExceptionis the typical example. They represent problems a caller can reasonably be expected to handle. - Unchecked exceptions extend
RuntimeException. The compiler does not force you to handle them.NullPointerException,IllegalArgumentExceptionandArrayIndexOutOfBoundsExceptionare of this kind. They usually indicate a bug in the code.
There is also Error, for serious JVM problems such as OutOfMemoryError. You do not normally catch those.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 1. try / catch / finally
for (String input : new String[]{"42", "abc", ""}) {
try {
int number = Integer.parseInt(input);
System.out.println("Parsed " + number + ", 100 / number = " + (100 / number));
} catch (NumberFormatException e) {
System.out.println("Not a number: '" + input + "'");
} finally {
System.out.println("Checked " + input.length() + " characters");
}
}
// 2. Custom checked exception
try {
withdraw(500, 800);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + " (short by " + e.getShortfall() + ")");
}
// 3. Multi-catch and wrapping the cause
try {
loadConfig("timeout=abc");
} catch (ConfigException e) {
System.out.println(e.getMessage() + " <- " + e.getCause().getClass().getSimpleName());
}
// 4. try-with-resources closes in reverse order, even after an exception
try (Resource first = new Resource("first");
Resource second = new Resource("second")) {
System.out.println("Using resources");
throw new IllegalStateException("boom");
} catch (IllegalStateException e) {
System.out.println("Caught " + e.getMessage());
}
// 5. Fail fast with unchecked exceptions
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
static class InsufficientFundsException extends Exception {
private final double shortfall;
InsufficientFundsException(double shortfall) {
super("Not enough money in the account");
this.shortfall = shortfall;
}
double getShortfall() { return shortfall; }
}
static void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
}
static class ConfigException extends Exception {
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int loadConfig(String line) throws ConfigException {
try {
String[] parts = line.split("=");
return Integer.parseInt(parts[1]);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
throw new ConfigException("Bad configuration line: " + line, e);
}
}
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
System.out.println("Open " + name);
}
@Override
public void close() {
System.out.println("Close " + name);
}
}
static void setAge(int age) {
if (age < 0 || age > 130) {
throw new IllegalArgumentException("age out of range: " + age);
}
}
}
Walking through it
The first loop feeds three inputs through Integer.parseInt. For "42" everything works. For "abc" and the empty string, NumberFormatException is thrown and caught. The finally block runs every time, with or without an exception. Look at the output carefully: the line "Checked 2 characters" appears after the success as well. Use finally for cleanup that must always happen. Since Java 7, try-with-resources is the preferred way for that purpose.
The custom InsufficientFundsException extends Exception, so it is checked. The method declares throws InsufficientFundsException, and the caller must handle it. The exception carries data, the shortfall, as well as the message. Whether to make a custom exception checked or unchecked is a long-running debate. My own rule: checked for conditions that a caller can recover from and that are part of the method's normal contract, unchecked for programming errors. Many modern libraries use unchecked exceptions almost everywhere, because checked ones make lambdas and layers of code noisy.
In loadConfig, one catch handles two exception types with |. We then throw a different exception, ConfigException, and pass the original as the cause. Wrapping like this lets each layer speak in its own terms without losing the original stack trace. When the trace is printed, you see "Caused by". Never throw away the cause.
The try-with-resources statement declares resources in brackets. Anything that implements AutoCloseable qualifies. The output shows that both resources are closed in reverse order, "second" before "first", before the catch block runs, even though the body threw an exception. Use it for files, streams, database connections and anything with a close method. Writing manual finally blocks for this is old style and easy to get wrong.
Finally, setAge validates its argument and throws IllegalArgumentException early. Failing at the point of the mistake makes bugs much easier to find than letting a bad value travel through the program.
Rules I follow
- Catch the most specific exception you can handle. Do not catch
ExceptionorThrowablebroadly unless you are at the top of the program or a request. - Never leave a catch block empty. At minimum, log the exception.
- Log or handle an exception once. Logging and then rethrowing at every layer fills the log with duplicates.
Common mistakes
- Swallowing exceptions with an empty catch.
- Catching
Exceptionand printing onlye.getMessage(). You lose the stack trace. - Forgetting to pass the cause when wrapping.
Try it yourself
- Write a method
parsePositive(String text)that throwsIllegalArgumentExceptionwith a clear message for non-numbers and for zero or negative values. - Create a custom checked exception
OutOfStockExceptionand use it in a methodbuy(String item, int qty). - Write a resource class that fails in its constructor for the second resource, and observe which resources get closed.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 1. try / catch / finally
for (String input : new String[]{"42", "abc", ""}) {
try {
int number = Integer.parseInt(input);
System.out.println("Parsed " + number + ", 100 / number = " + (100 / number));
} catch (NumberFormatException e) {
System.out.println("Not a number: '" + input + "'");
} finally {
System.out.println("Checked " + input.length() + " characters");
}
}
// 2. Custom checked exception
try {
withdraw(500, 800);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + " (short by " + e.getShortfall() + ")");
}
// 3. Multi-catch and wrapping the cause
try {
loadConfig("timeout=abc");
} catch (ConfigException e) {
System.out.println(e.getMessage() + " <- " + e.getCause().getClass().getSimpleName());
}
// 4. try-with-resources closes in reverse order, even after an exception
try (Resource first = new Resource("first");
Resource second = new Resource("second")) {
System.out.println("Using resources");
throw new IllegalStateException("boom");
} catch (IllegalStateException e) {
System.out.println("Caught " + e.getMessage());
}
// 5. Fail fast with unchecked exceptions
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
static class InsufficientFundsException extends Exception {
private final double shortfall;
InsufficientFundsException(double shortfall) {
super("Not enough money in the account");
this.shortfall = shortfall;
}
double getShortfall() { return shortfall; }
}
static void withdraw(double balance, double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
}
static class ConfigException extends Exception {
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int loadConfig(String line) throws ConfigException {
try {
String[] parts = line.split("=");
return Integer.parseInt(parts[1]);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
throw new ConfigException("Bad configuration line: " + line, e);
}
}
static class Resource implements AutoCloseable {
private final String name;
Resource(String name) {
this.name = name;
System.out.println("Open " + name);
}
@Override
public void close() {
System.out.println("Close " + name);
}
}
static void setAge(int age) {
if (age < 0 || age > 130) {
throw new IllegalArgumentException("age out of range: " + age);
}
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account