Skip to content

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.

Beginner 18 min read·Lesson 27 of 39 in Java Programming

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

Java
try {
int n = Integer.parseInt(text);
System.out.println(100 / n);
} catch (NumberFormatException e) {
System.out.println("not a number");
} catch (ArithmeticException e) {
System.out.println("cannot divide by zero");
} finally {
System.out.println("always runs");
}
void read(Path p) throws IOException { ... } // declares a checked exception
throw new IllegalStateException("not ready"); // raises one
  • 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

Java
public class Main {
public static void main(String[] args) {
String[] inputs = {"25", "0", "abc"};
for (String in : inputs) {
try {
int n = Integer.parseInt(in);
System.out.println("100 / " + n + " = " + 100 / n);
} catch (NumberFormatException e) {
System.out.println("'" + in + "' is not a number");
} catch (ArithmeticException e) {
System.out.println("division by zero: " + e.getMessage());
} finally {
System.out.println("-- processed " + in);
}
}
}
}
Output
100 / 25 = 4
-- processed 25
division by zero: / by zero
-- processed 0
'abc' is not a number
-- processed abc

Throwing and propagating

Java
public class Main {
static void setAge(int age) {
if (age < 0 || age > 150) throw new IllegalArgumentException("invalid age: " + age);
System.out.println("age set to " + age);
}
static void register(int age) {
setAge(age); // no try here: the exception propagates
System.out.println("registered");
}
public static void main(String[] args) {
try {
register(30);
register(-5);
System.out.println("never printed");
} catch (IllegalArgumentException e) {
System.out.println("Caught in main: " + e.getMessage());
}
}
}
Output
age set to 30
registered
Caught in main: invalid age: -5

More examples

Checked exceptions, multi-catch and finally ordering

Java
import java.io.IOException;
public class Main {
static String fetch(String source) throws IOException { // checked: callers must handle it
if (source.startsWith("bad")) throw new IOException("cannot reach " + source);
return "data from " + source;
}
static int parsePort(String s) {
try {
int p = Integer.parseInt(s);
if (p < 1 || p > 65535) throw new IllegalArgumentException("port out of range: " + p);
return p;
} finally {
System.out.println(" (finally runs even when returning or throwing)");
}
}
public static void main(String[] args) {
for (String src : new String[]{"server-1", "bad-host"}) {
try {
System.out.println(fetch(src));
} catch (IOException e) {
System.out.println("I/O problem: " + e.getMessage());
}
}
for (String s : new String[]{"8080", "99999", "http"}) {
try {
System.out.println("port " + parsePort(s));
} catch (NumberFormatException | IllegalStateException e) {
System.out.println("bad format: " + s);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
try {
Object o = "text";
Integer i = (Integer) o;
} catch (RuntimeException e) {
System.out.println(e.getClass().getSimpleName() + " caught as RuntimeException");
}
}
}
Output
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

  • fetch declares throws IOException; the compiler forces main to 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 RuntimeException handles any unchecked exception, here a ClassCastException; use broad catches sparingly.

Expected output

Running “Checked exceptions, multi-catch and finally ordering” prints exactly:

TextOutput
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

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

try { save(); } catch (Exception e) { }

Prefer

try { save(); } catch (IOException e) { System.err.println("Save failed: " + e.getMessage()); }

An empty catch hides failures, so the program continues in a broken state with no clue why.

Catching the general type first

Avoid

catch (Exception e) { ... }
catch (IOException e) { ... } // unreachable

Prefer

catch (IOException e) { ... }
catch (Exception e) { ... }

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

  1. 1
    Write a method that reads an int from a string and returns a default value on any parsing error.
  2. 2
    Write 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?
Practise this topic