Exception Handling in Java: try, catch, finally and throw Explained
Learn exception handling in Java — try, catch, finally, common exceptions like NullPointerException, checked vs unchecked, and throwing your own, all beginner-friendly.
Welcome to Level 3, where we move from "how Java is structured" to the powerful tools you'll use in real programs every day. First up: exceptions — Java's way of handling errors gracefully. You've almost certainly seen a program crash with a scary red message like NullPointerException. This lesson shows you what those are and, crucially, how to handle them so your program stays in control instead of falling over.
What is an exception?
An exception is an event that disrupts the normal flow of your program — something went wrong at runtime. Dividing by zero, reading a file that doesn't exist, or accessing an array index that's out of bounds all throw exceptions. If you don't handle them, the program crashes and prints a stack trace.
int[] nums = {1, 2, 3};
System.out.println(nums[5]); // 💥 ArrayIndexOutOfBoundsException — program stops here
The try-catch block
The core tool is try-catch. You put the risky code in try, and if it throws an exception, the matching catch block runs instead of crashing:
try { int result = 10 / 0; // throws ArithmeticException System.out.println(result); } catch (ArithmeticException e) { System.out.println("You can't divide by zero!"); } System.out.println("Program continues normally."); // this still runs ✓
Instead of crashing, the program prints your friendly message and keeps going. That's the whole point: you stay in control. The e is the exception object — you can call e.getMessage() on it to see what went wrong.
The finally block
A finally block runs no matter what — whether an exception happened or not. It's used for cleanup, like closing a file or a database connection:
try { // risky code } catch (Exception e) { // handle the error } finally { System.out.println("This always runs — success or failure."); }
Common exceptions you'll meet
| Exception | When it happens |
|---|---|
NullPointerException |
Using a variable that is null (the #1 Java error!) |
ArrayIndexOutOfBoundsException |
Accessing an invalid array index |
ArithmeticException |
Illegal maths, e.g. dividing by zero |
NumberFormatException |
Converting bad text to a number (Integer.parseInt("abc")) |
Checked vs unchecked (a quick distinction)
Java has two families of exceptions:
- Unchecked (runtime) — programming bugs like
NullPointerException. Java doesn't force you to handle them; you fix the cause. - Checked — external problems Java forces you to deal with, like
IOExceptionwhen reading a file. The compiler won't let you ignore them: you must eithertry-catchthem or declarethrowson your method.
Throwing your own exceptions
You can raise an exception yourself with throw when a rule is broken — great for validation:
void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } this.age = age; }
catch block: catch (Exception e) { }. This hides the error and makes bugs almost impossible to find. At minimum, log the error (e.printStackTrace() or a logger) so you know it happened. Handle exceptions — don't hide them.Good exception handling is one of the biggest differences between beginner code and production code. In this website's own code, risky operations are wrapped so that if something fails — a bad request, a missing record — the app responds with a clean error page instead of crashing for everyone. Early on I used to either ignore exceptions or let them crash things; learning to catch them meaningfully (handle, log, or rethrow with context) was a real turning point in writing software people can actually rely on.
Key takeaways
- An exception is a runtime error; unhandled, it crashes your program.
- Wrap risky code in
tryand handle failures incatch;finallyalways runs (cleanup). - Know the common ones — especially
NullPointerException. - Use
throwto raise your own; never leave acatchblock empty.
← Previous: Lesson 19 — this, super & final
Next: Lesson 21 — The Collections Framework →