Module 8 · Exceptions and File Handling — topic 1 of 3
Exception Handling
What exceptions are, the Throwable hierarchy, try/catch/finally, multi-catch, checked versus unchecked exceptions, throw and throws, and reading stack traces.
Learning objectives
- Handle exceptions with try, catch and finally
- Distinguish checked from unchecked exceptions and declare them with throws
- Read a stack trace to locate the cause of an error
Definition
An exception is an object that signals an abnormal condition. When one is thrown, normal execution stops and the JVM looks up the call stack for a matching catch block; if none is found, the thread terminates and a stack trace is printed.
Introduction
Things go wrong: a user types letters where a number is expected, a file is missing, a network connection drops. In C you'd check return codes after every call. Java uses exceptions instead: the code that detects a problem *throws* an exception, and code further up the call stack that knows what to do *catches* it.
Why it matters
Robust programs handle bad input and failures gracefully instead of crashing.
Java's checked exceptions force you to think about failures such as missing files — and the compiler won't let you forget.
Detailed explanation
The hierarchy. Throwable has two branches. Error (OutOfMemoryError, StackOverflowError) signals serious JVM problems you normally don't catch. Exception covers problems programs can handle; its subclass RuntimeException and everything below it are *unchecked*.
Checked exceptions (IOException, SQLException, InterruptedException) represent foreseeable failures outside the program's control. The compiler requires you to either catch them or declare them with throws in the method signature.
Unchecked exceptions (NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException, ArithmeticException, NumberFormatException) usually indicate programming errors or invalid arguments. Catching them is optional.
try / catch / finally. Code that might fail goes in try. Each catch (Type e) handles one type (and its subclasses); list more specific types first. catch (A | B e) handles several unrelated types in one block. finally always runs — after normal completion, after a caught exception, and even when an exception propagates — which makes it the place for clean-up.
throw and throws. throw new IllegalArgumentException("age must be positive"); raises an exception. void load() throws IOException warns callers that the method may throw a checked exception.
Stack traces list the exception type and message followed by the chain of method calls, innermost first, with file names and line numbers. Read from the top to find where it was thrown, then look for the first line in *your* code.
Good practice. Catch exceptions where you can do something useful (retry, report, use a default). Never swallow them silently with an empty catch block.
Syntax
- Order catch blocks from most specific to most general.
- e.getMessage() gives the message; e.printStackTrace() prints the trace.
- A finally block runs even if the try block returns.
Code examples
Catching specific exceptions
100 / 25 = 4 -- processed 25 division by zero: / by zero -- processed 0 'abc' is not a number -- processed abc
Throwing and propagating
age set to 30 registered Caught in main: invalid age: -5
More examples
Checked exceptions, multi-catch and finally ordering
data from server-1 I/O problem: cannot reach bad-host (finally runs even when returning or throwing) port 8080 (finally runs even when returning or throwing) port out of range: 99999 (finally runs even when returning or throwing) bad format: http ClassCastException caught as RuntimeException
Step-by-step explanation
fetchdeclaresthrows IOException; the compiler forcesmainto catch it (or declare it too).- In
parsePort, the finally block runs before the value is returned *and* before an exception leaves the method — that's why its message appears before each result. - NumberFormatException is a subclass of IllegalArgumentException, so the multi-catch for it must come before the IllegalArgumentException handler.
- A multi-catch (
A | B) can't list types where one is a subclass of the other, which is why it pairs NumberFormatException with the unrelated IllegalStateException. - Catching the general
RuntimeExceptionhandles any unchecked exception, here a ClassCastException; use broad catches sparingly.
Expected output
Running “Checked exceptions, multi-catch and finally ordering” prints exactly:
Practical applications
- Validating user input in forms and APIs
- Handling network and file failures with retries or error messages
- Web frameworks that turn exceptions into HTTP error responses
- Transaction rollback when a database operation fails
Best practices
- Catch the most specific exception you can handle.
- Include useful details in exception messages.
- Use exceptions for exceptional situations, not ordinary control flow.
Common mistakes
Swallowing exceptions
Avoid
Prefer
An empty catch hides failures, so the program continues in a broken state with no clue why.
Catching the general type first
Avoid
Prefer
The first matching catch wins, so a general handler before a specific one makes the specific one unreachable — a compile error.
Important notes
- Since Java 14, NullPointerException messages name the null variable or expression (helpful NPEs).
- If both the try block and the finally block throw, the exception from finally replaces the original — another reason to keep finally blocks simple.
Key takeaways
- Checked exceptions must be caught or declared; unchecked ones are optional to handle.
- Catch specific types first; finally always runs.
- throw raises an exception; throws declares that a method may throw one.
Try it yourself
- 1Write a method that reads an int from a string and returns a default value on any parsing error.
- 2Write a loop that keeps asking for a number between 1 and 10 until valid input is entered, using exceptions for non-numeric input.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
11 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhich is a checked exception?
- BeginnerWhat does the throws clause in `void read() throws IOException` mean?