Intermediate · Exceptions and generics · topic 26 of 60 · 25 min
Exceptions: try, catch and finally
Explanation
What happens when something fails
When code hits a problem, such as dividing by zero or reading a missing file, Java creates an exception object and throws it. The current method stops; the exception travels back up the call stack until a matching catch block handles it. If nothing catches it, the thread dies and the stack trace is printed.
static int perHead(int total, int people) {
return total / people; // ArithmeticException when people is 0
}
public static void main(String[] args) {
try {
System.out.println(perHead(1200, 4)); // 300
System.out.println(perHead(1200, 0)); // throws
System.out.println("not reached");
} catch (ArithmeticException e) {
System.out.println("Cannot split: " + e.getMessage()); // / by zero
} finally {
System.out.println("Bill split done"); // always runs
}
}The exception hierarchy
Throwable
├── Error (OutOfMemoryError, StackOverflowError: do not catch)
└── Exception
├── IOException, SQLException… (checked: must be handled or declared)
└── RuntimeException (unchecked)
├── NullPointerException
├── IllegalArgumentException
├── ArithmeticException
└── IndexOutOfBoundsException…Several catch blocks and multi-catch
try {
int qty = Integer.parseInt(input);
int[] stock = new int[5];
stock[qty] = 1;
} catch (NumberFormatException e) {
System.out.println("Quantity must be a number");
} catch (ArrayIndexOutOfBoundsException | NegativeArraySizeException e) { // multi-catch
System.out.println("No such shelf: " + e.getMessage());
}Java checks catch blocks from top to bottom and runs the FIRST one whose type matches. A catch for a parent type placed before a catch for its child type makes the child catch unreachable, which is a compile error ("exception … has already been caught"). So order catch blocks from most specific to most general.
finally
finally runs after try (and catch), whether an exception happened or not, and even if the try block returns. Use it for clean-up, such as releasing a lock or closing a resource (though try-with-resources, topic 3, is better for closing). Never put return in finally: it silently overrides the try's return and swallows exceptions.
static int test() {
try {
return 1;
} finally {
System.out.println("finally runs"); // printed before the method returns 1
}
}Useful methods on exceptions
- getMessage(): the human-readable message.
- printStackTrace(): prints the full stack trace (use a logger in real apps).
- getCause(): the underlying exception, if this one wraps another.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Exceptions: try, catch and finally · 1/6
In this lesson you will handle errors with exceptions.
Prefer a video by a teacher? Find free videos on “java exception handling try catch finally hierarchy” on YouTube ↗
In real life: Importing a bank statement
A finance app imports a CSV statement line by line. A bad line (a non-numeric amount) throws NumberFormatException; the importer catches it for that line, records the line number, and continues with the rest instead of failing the whole import.
String[] lines = {"2026-01-02,1500", "2026-01-03,abc", "2026-01-05,-200"};
int ok = 0;
java.util.List<String> bad = new java.util.ArrayList<>();
for (int i = 0; i < lines.length; i++) {
try {
double amount = Double.parseDouble(lines[i].split(",")[1]);
ok++;
} catch (NumberFormatException e) {
bad.add("line " + (i + 1));
}
}
System.out.println(ok + " imported, skipped " + bad); // 2 imported, skipped [line 2]Practice (0/3 done)
What does this print? try { System.out.print("A"); int x = 5 / 0; System.out.print("B"); } catch (ArithmeticException e) { System.out.print("C"); } finally { System.out.print("D"); }
Why does this NOT compile? try { … } catch (Exception e) { … } catch (NumberFormatException e) { … }
Write a program that asks for the number of people and a bill amount (as text), and prints the share per person. Handle NumberFormatException (not a number) and ArithmeticException (0 people) with separate friendly messages, and print "Thank you" in finally.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Checked vs unchecked exceptions and throwing your ownExceptions and generics · same module
- try-with-resources and clean-upExceptions and generics · same module
- GenericsExceptions and generics · same module
- Exceptions: try, catch, finally and custom exceptionsC# and .NET · Exceptions, delegates, events and async
- Error handling: try, catch, finally and throwJavaScript Programming (language in depth) · Modules, errors, JSON and dates
- Errors and exceptionsPython Programming · Errors, modules and the standard library
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which should you normally NOT catch?
Answer: OutOfMemoryError
Errors signal serious JVM problems.
When does finally run?
Answer: Always, even after return
finally always runs (except if the JVM exits).
What does catch (A | B e) mean?
Answer: One block that handles either A or B
Multi-catch handles several unrelated types in one block.
What happens to an exception nobody catches in main?
Answer: The thread ends and the stack trace is printed
Uncaught exceptions end the thread.
What happens to an exception that nobody catches?Related
Answer: The program crashes and shows the error
Unhandled exceptions end the process.
When does finally run?Related
Answer: Always, after try (and catch)
finally runs in every case, even after return.
When does the else block of a try statement run?Related
Answer: Only when the try block raised no exception
else runs only on success. finally is the block that runs every time.
Which base class should your own exception types usually derive from?Related
Answer: std::exception (often via std::runtime_error)
Then generic handlers for std::exception catch them too, and what() works.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “Exceptions and generics” before its exam: Checked vs unchecked exceptions and throwing your own, try-with-resources and clean-up, Generics, Avoiding NullPointerException.
- Module 6 exam: Exceptions and generics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, The collections framework. 60 topics left in the course before the final exam.