Explain it simply
Explain it simply
An exception is an alarm the program raises when it cannot carry on with the current job. Reading an array index that does not exist, turning "two" into a number, or opening a missing file all make Java throw an exception object. If nobody catches it, the whole program stops with a stack trace.
A try block marks code that might fail. A catch block hears the alarm and recovers, for example by showing a friendly message or using a default value. A finally block is the clean-up step that runs whether the work succeeded or failed.
Problem → Why → Solution
The problem: one bad input crashes the whole app
The program below adds up quantities typed by users. It works for "3" and "5", but as soon as someone types "ten", Integer.parseInt() throws a NumberFormatException and it propagates straight out of main(). The remaining orders are never processed and the total is never printed.
An even worse fix is to silence the crash with an empty catch (Exception e) {}. The program no longer crashes, but nobody learns that the data was bad, and a wrong total quietly goes out.
public class Main {
public static void main(String[] args) {
String[] quantities = {"3", "ten", "5"};
int total = 0;
for (String q : quantities) {
total += Integer.parseInt(q); // "ten" -> NumberFormatException, program dies
}
System.out.println("Total: " + total); // never reached
}
}Why does this happen?
When an exception is thrown, Java walks back up the method call stack looking for a matching catch block. If it reaches the top of main() without finding one, the thread dies. The cure is not hiding exceptions but catching the specific type at the place that can actually recover, and saying clearly what went wrong.
Core concept: how an exception travels
In Java every exception is an object, and Throwable sits at the top of the class hierarchy. Below it are two branches: Error, for problems the JVM itself cannot recover from such as OutOfMemoryError, and Exception, for problems application code is expected to handle. Inside Exception, RuntimeException and its subclasses are called unchecked; every other exception is checked.
The difference lives in the compiler. A method that can throw a checked exception such as IOException must either catch it or declare throws IOException in its signature; otherwise you get an "unreported exception" compile error. Unchecked exceptions such as NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException and IllegalArgumentException usually signal a programming bug or bad input, so the compiler does not force you to handle them.
Once an exception is thrown, the rest of the try block is skipped and Java checks the catch blocks from top to bottom. Only the first catch whose type matches the exception object runs. That is why specific types go above general ones: putting catch (Exception e) first would make the later blocks unreachable, and the compiler rejects that with a "has already been caught" error. When two blocks would do the same work, combine them with a multi-catch such as catch (NumberFormatException | ArrayIndexOutOfBoundsException e).
The finally block runs when the try succeeds, when a catch runs, and even when the try block executes return. If an exception is not caught here and keeps propagating, finally still runs first, on the way out.
You can also raise an exception yourself with the throw keyword, as in throw new IllegalArgumentException("..."). When a method cannot keep its promise, throwing an exception with a message that explains why is clearer than returning a misleading value. Catch an exception only in the layer that can actually recover from it; otherwise let it travel upward.
- A line in try throws
- Rest of the try block is skipped
- First matching catch runs
- finally always runs
- No match: climb to the caller
Catch where you can recover, not wherever the error happens to appear.
General pattern
try {
riskyWork();
} catch (SpecificException e) {
recover(e);
} catch (OtherException | ThirdException e) {
report(e);
} finally {
cleanUp();
}
void method() throws CheckedException { throw new CheckedException("why"); }Put the risky code in try and write catch blocks from specific to general; | joins several types into one multi-catch. finally is optional and always runs. A checked exception you do not catch must be declared with throws in the method signature.
Example: checking three inputs against an array
This example loops over three inputs so you can see a success, an out-of-range index such as numbers[5] and a value that is not a number side by side. Compare the output with the code to see which catch runs for each input and when finally runs.
public class Main {
static int pick(int[] numbers, String rawIndex) {
int index = Integer.parseInt(rawIndex); // may throw NumberFormatException
return numbers[index]; // may throw ArrayIndexOutOfBoundsException
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
String[] inputs = {"1", "5", "two"};
for (String input : inputs) {
try {
System.out.println("Value: " + pick(numbers, input));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index " + input + ". Choose 0 to 2.");
} catch (NumberFormatException e) {
System.out.println("Not a number: " + input);
} finally {
System.out.println("Checked input " + input);
}
}
}
}Code breakdown
- Line 3
int index = Integer.parseInt(rawIndex); // may throw NumberFormatExceptionIf a string like "two" cannot become an int, parseInt() throws NumberFormatException. pick() has no catch of its own, so the exception climbs straight to the try in main().
- Line 4
return numbers[index]; // may throw ArrayIndexOutOfBoundsExceptionnumbers only has indexes 0, 1 and 2, so index 5 throws ArrayIndexOutOfBoundsException. Java always checks array bounds, so you never silently read garbage memory.
- Line 13
System.out.println("Value: " + pick(numbers, input));If pick() throws, println() is never called, which is why no Value: line appears for "5" or "two".
- Lines 14-17
} catch (ArrayIndexOutOfBoundsException e) {The two catch blocks handle different exception types with different messages. For each exception only the one matching catch runs.
- Line 18
} finally {finally runs for all three inputs: after the successful "1" and after the catch blocks for "5" and "two". That is why there are three Checked input lines.
Value: 20
Checked input 1
Invalid index 5. Choose 0 to 2.
Checked input 5
Not a number: two
Checked input two- Start running the try block
- Check whether anything throws
- Look for a matching catch
- Run finally
No exception
try finishes -> finally -> next line
Matching catch
catch -> finally -> next line
No matching catch
finally -> exception goes to the caller
Your own exceptions and throws
When a domain rule is broken, such as an account without enough money, you can create your own checked exception by extending Exception. Because it is checked, every caller of withdraw() is forced to handle that case instead of forgetting it. A caller bug such as a negative amount is better reported with an unchecked IllegalArgumentException.
public class Main {
static class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
static int withdraw(int balance, int amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive: " + amount);
}
if (amount > balance) {
throw new InsufficientFundsException("need " + amount + ", have " + balance);
}
return balance - amount;
}
public static void main(String[] args) {
try {
System.out.println("Left: " + withdraw(100, 30));
System.out.println("Left: " + withdraw(100, 250));
} catch (InsufficientFundsException e) {
System.out.println("Declined: " + e.getMessage());
}
}
}This program prints "Left: 70" and then "Declined: need 250, have 100". When you catch a low-level exception and rethrow a more meaningful one, pass the original as the cause, as in new ConfigException("...", e). The stack trace then keeps a "Caused by:" section that points to the root problem.
try-with-resources
Files, database connections and network sockets must be closed after use. Declare AutoCloseable objects inside try ( ... ) and Java calls close() automatically when the block ends, even if an exception was thrown. Resources close in the reverse order they were opened, and the catch block runs only after they are closed.
public class Main {
static class Connection implements AutoCloseable {
private final String name;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
void send(String message) {
if (message.isEmpty()) {
throw new IllegalStateException("empty message");
}
System.out.println(name + " sent " + message);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
try (Connection db = new Connection("db");
Connection cache = new Connection("cache")) {
db.send("hello");
cache.send("");
} catch (IllegalStateException e) {
System.out.println("caught: " + e.getMessage());
}
}
}The output is open db, open cache, db sent hello, close cache, close db, caught: empty message. Notice that cache, opened last, is closed first, and the catch runs at the very end.
In real projects
Where this shows up in real projects
A backend service handles exceptions in layers. The repository layer catches the database driver's SQLException and rethrows a domain exception such as OrderNotFoundException with the original as its cause. The service layer enforces business rules, and the web layer, for example a global exception handler in Spring, turns each exception type into an HTTP status such as 404, 400 or 500 with a JSON message the client understands.
Logs record the full stack trace and cause chain so the root problem can be found when something breaks in production, while users only see a message without internal details. Reading files, calling HTTP clients and borrowing database connections all use try-with-resources as the standard, because a resource leak rarely fails immediately; it shows up hours later when the server runs out of connections. Tests use assertThrows to prove that bad input produces the right exception type.
Common mistakes
Common mistakes
1. Swallowing an exception with an empty catch
catch (Exception e) {} hides the crash but also hides the bug. The program keeps running in a broken state and the problem resurfaces later somewhere that makes no sense. If you cannot recover, do not catch; if you do catch, at least log it and decide what happens next.
2. Dropping the cause when wrapping
Writing throw new RuntimeException("load failed"); throws away the original IOException's message and stack trace. Pass e as the second argument, throw new RuntimeException("load failed", e);, so the "Caused by:" section still shows the file name and line number.
3. Putting the general catch first
Placing catch (Exception e) above catch (NumberFormatException e) makes the second block unreachable, which is a compile error. Always list a subclass before its superclass.
4. Returning from finally
A return inside finally silently discards any exception thrown in the try block. Keep finally for clean-up only.
Best practices
Best practices
- Catch only the specific types you can handle; reserve catch (Exception e) for the outermost boundary of the program.
- Include the offending value in the message: "port out of range: 70000" is far more useful than "invalid input".
- Open everything that needs closing with try-with-resources.
- Do not use exceptions for normal control flow such as leaving a loop; if a simple if can check it, use the if.
Mini challenge
Mini challenge: validate a config port
Write parsePort() to validate port strings read from a config file. Every invalid case throws your own checked ConfigException, and when the text is not a number the original NumberFormatException must be kept as the cause.
- ConfigException extends Exception and has (message) and (message, cause) constructors
- A null or blank string gives "port is missing"
- A non-number wraps the NumberFormatException as the cause
- Outside 1 to 65535 gives "port out of range: <port>"
- main() prints each input's result, or the message and the cause's class name
public class Main {
static class ConfigException extends Exception {
// TODO: constructor (String message)
// TODO: constructor (String message, Throwable cause)
}
static int parsePort(String raw) throws ConfigException {
// TODO: reject null or blank input
// TODO: parse with Integer.parseInt, wrapping NumberFormatException as the cause
// TODO: reject ports outside 1..65535
return 0;
}
public static void main(String[] args) {
String[] inputs = {"8080", " 443 ", "http", "70000", ""};
// TODO: for each input print "OK <port>" or "Rejected: <message> (cause: <name>)"
}
}Expected: The program should print these five lines: OK 8080 OK 443 Rejected: port is not a number: http (cause: NumberFormatException) Rejected: port out of range: 70000 (cause: none) Rejected: port is missing (cause: none)
Show hint
Calling super(message, cause) in the constructor makes Exception store the cause, and e.getCause() returns it later. Use getClass().getSimpleName() for the cause's class name; getCause() returns null when there is no cause.
Show solution
public class Main {
static class ConfigException extends Exception {
ConfigException(String message) {
super(message);
}
ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
static int parsePort(String raw) throws ConfigException {
if (raw == null || raw.isBlank()) {
throw new ConfigException("port is missing");
}
int port;
try {
port = Integer.parseInt(raw.trim());
} catch (NumberFormatException e) {
throw new ConfigException("port is not a number: " + raw, e);
}
if (port < 1 || port > 65535) {
throw new ConfigException("port out of range: " + port);
}
return port;
}
public static void main(String[] args) {
String[] inputs = {"8080", " 443 ", "http", "70000", ""};
for (String input : inputs) {
try {
System.out.println("OK " + parsePort(input));
} catch (ConfigException e) {
Throwable cause = e.getCause();
String causeName = cause == null ? "none" : cause.getClass().getSimpleName();
System.out.println("Rejected: " + e.getMessage() + " (cause: " + causeName + ")");
}
}
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- When an exception is thrown, the rest of the try is skipped and the first matching catch runs; with no match it climbs to the caller.
- Checked exceptions such as IOException must be caught or declared with throws; the RuntimeException family is unchecked.
- Order catch blocks from specific to general; finally always runs.
- Keep the cause when wrapping, and close resources with try-with-resources.
Java SE 25 API Specification — Oracle