Lesson 18: Exception vs. RuntimeException in Java: What’s the Deal?

Let’s be real—exceptions in Java can be a pain. But they exist for a good reason: they help us deal with problems in a controlled way instead of letting our programs crash like a poorly built Jenga tower.

Now, if you’ve been coding in Java for a bit, you’ve probably heard of Exception and RuntimeException. They sound similar, but they behave quite differently. So let’s break it down and figure out when each one pops up, why they matter, and what other sneaky exceptions might surprise you.


1. The Key Difference Between Exception and RuntimeException

In Java, everything related to errors and exceptions comes from the Throwable class, which has two big categories:

  • Error – Serious issues like OutOfMemoryError that usually mean “game over” for your app.
  • Exception – Things you might be able to recover from.

The Exception family is split into two groups:

  • Checked exceptions (things Java forces you to handle) – These extend Exception but not RuntimeException.
  • Unchecked exceptions (things Java doesn’t force you to handle) – These extend RuntimeException.

Checked Exceptions (Exception) – Java’s “Mandatory Safety Net”

Checked exceptions are things Java makes you deal with, whether you like it or not. If a method can throw one, you either have to catch it or declare it with throws.

Example: Trying to read a file that doesn’t exist (FileNotFoundException).

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(new File("file.txt")); // Might throw FileNotFoundException
        } catch (FileNotFoundException e) {
            System.out.println("Oops! The file is missing: " + e.getMessage());
        }
    }
}

If you don’t handle it, Java won’t even compile your code.


Unchecked Exceptions (RuntimeException) – Java’s “You Should Know Better” Group

Unchecked exceptions are things that happen due to bad coding decisions (yep, it’s on you). Java doesn’t force you to catch them because they’re usually things you should’ve prevented in the first place.

Example: Dividing by zero.

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int result = 10 / 0; // Boom! ArithmeticException
        System.out.println(result);
    }
}

Your program will crash at runtime, but Java won’t warn you about it at compile time.


Quick Comparison: Checked vs. Unchecked Exceptions

FeatureChecked Exceptions (Exception)Unchecked Exceptions (RuntimeException)
Do you have to handle it?Yes, or Java won’t compileNo, but you probably should
When does it show up?During compilationWhile the program is running
ExamplesIOException, SQLExceptionNullPointerException, IndexOutOfBoundsException
Who’s responsible?External factors (files, network, database)You (bad code, logical mistakes)

2. Other Exception Types You Should Know

Aside from Exception and RuntimeException, Java has a bunch of other exception types that might catch you off guard.

1. Error – When the JVM Says “Nope”

Errors are nasty. They don’t come from your code, they come from the system itself.

Examples:

  • OutOfMemoryError – Java ran out of memory.
  • StackOverflowError – Infinite recursion killed your program.

Here’s how you can accidentally cause a StackOverflowError:

public class StackOverflowExample {
    public static void recursive() {
        recursive(); // Calls itself forever
    }

    public static void main(String[] args) {
        recursive(); // Crash incoming...
    }
}

2. IOException – The “I/O Messed Up” Exception (Checked)

Java throws IOException when something goes wrong with file handling, network connections, or input/output operations.

Example:

import java.io.FileReader;
import java.io.IOException;

public class IOExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader("file.txt"); // Might throw IOException
            reader.read();
        } catch (IOException e) {
            System.out.println("Something went wrong with file handling: " + e.getMessage());
        }
    }
}

3. SQLException – Database Drama (Checked)

SQL-related operations can go south for many reasons—bad queries, connection failures, or database constraints.

Example:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SQLExceptionExample {
    public static void main(String[] args) {
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "pass");
        } catch (SQLException e) {
            System.out.println("Database connection failed: " + e.getMessage());
        }
    }
}

4. NullPointerException – The Classic Java Nightmare (Unchecked)

Trying to use null like it’s a real object? Boom. NullPointerException.

public class NullPointerExample {
    public static void main(String[] args) {
        String text = null;
        System.out.println(text.length()); // Crash!
    }
}

5. IllegalArgumentException – When You Give a Method Garbage (Unchecked)

This happens when you pass an argument that doesn’t make sense.

public class IllegalArgumentExample {
    public static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age can't be negative!");
        }
    }

    public static void main(String[] args) {
        setAge(-5); // Throws IllegalArgumentException
    }
}

6. IndexOutOfBoundsException – You Went Too Far (Unchecked)

Ever tried accessing index 10 in a list with only 5 elements? That’s how you get an IndexOutOfBoundsException.

import java.util.ArrayList;
import java.util.List;

public class IndexOutOfBoundsExample {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        System.out.println(list.get(5)); // Crash!
    }
}

3. Final Thoughts

So, what did we learn?

  1. Checked exceptions (Exception) are for expected problems (like missing files) that Java forces you to handle.
  2. Unchecked exceptions (RuntimeException) are for unexpected problems (like NullPointerException) that Java assumes are your fault.
  3. Errors (Error) are the worst—they usually mean your program is toast.

When coding, don’t just silence exceptions with empty catch blocks. Handle them properly, log useful messages, and avoid writing code that causes unchecked exceptions in the first place.

Leave a Reply

Your email address will not be published. Required fields are marked *