Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Exception Handling: Try-Catch and Exception Types

This lesson is built with resources from youtube.com, stackoverflow.com and 1 more site.

Hello! Welcome to the next lesson in our journey to master backend development with Java and Spring Boot.

In our last session, we explored the Java Collections Framework, drawing parallels between List, Set, Map and their JavaScript counterparts. We also saw how Java Streams provide a powerful, functional way to process data, similar to chaining array methods in your MERN projects. So far, we've focused on the "happy path"—what happens when our code runs as expected. But in real-world systems, things go wrong. A file might be missing, a network connection might drop, or a user might provide invalid input.

Today, we'll tackle how Java manages these situations through its robust exception handling mechanism. You're familiar with try...catch from JavaScript, but Java introduces a formal, compile-time distinction between different types of errors that is fundamental to writing reliable backend code.

Our goal for this lesson is to handle exceptions using try-catch blocks and, most importantly, understand the critical difference between checked and unchecked exceptions.


1. The Core Idea: What is an Exception?

An exception is an event that occurs during the execution of a program that disrupts its normal flow. In Java, when an error occurs, an object representing that error is created and "thrown." This is conceptually the same as throw new Error() in JavaScript. The system then looks for a piece of code to handle it.

The most common way to handle an exception is with a try-catch block, which has a structure almost identical to what you already know.

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to run if an exception of ExceptionType occurs
} finally {
    // Code that will always run, whether an exception occurred or not.
    // Perfect for cleanup, like closing a file or a database connection.
}

While the syntax is familiar, the key difference in Java—and a concept that doesn't exist in JavaScript or TypeScript—is that the compiler distinguishes between two major categories of exceptions: checked and unchecked.



2. Unchecked Exceptions: The Programmer's Fault

Let's start with the type of exception that behaves most like a standard JavaScript error: the unchecked exception.

Unchecked exceptions represent problems that are typically the result of programming errors. They are things that could, and should, have been avoided by writing better code.

Common examples include:

  • NullPointerException: Trying to call a method on a null object. (Your code should have checked for null.)
  • ArrayIndexOutOfBoundsException: Accessing an array with an invalid index. (Your code should have checked the array's bounds.)
  • NumberFormatException: Trying to parse a non-numeric string like "abc" into a number. (Your code should have validated the input.)

Technically, all classes that inherit from java.lang.RuntimeException are unchecked. The compiler does not force you to handle them. Your code will compile just fine, but if the exception occurs at runtime, your program will crash.

This video provides clear, practical examples of these common unchecked exceptions.

Hands-on Java - Checked and Unchecked Exceptions - Day 28

The video 'Hands-on Java - Checked and Unchecked Exceptions' from Caleb Curry starts with great examples of common runtime errors. This will feel very familiar to your experience in JavaScript.

Watch the sections demonstrating NumberFormatException (1:23 - 2:51) and IndexOutOfBoundsException (2:51 - 3:50). Notice how the code compiles but crashes when run.


3. Checked Exceptions: The World's Fault

Now for the concept that is new and unique to Java: checked exceptions.

Checked exceptions represent problems that are typically due to external factors outside of your program's control. These are recoverable conditions.

Common examples include:

  • IOException: An error occurred during an input/output operation, like reading from a network stream that just closed.
  • FileNotFoundException: Trying to read a file that doesn't exist. The file path might be correct, but the file was deleted by another process.
  • SQLException: A database reports an error during a query.

Technically, any class that inherits from java.lang.Exception but not from RuntimeException is a checked exception. The Java compiler checks that you have handled these potential errors. If you call a method that can throw a checked exception, your code will not compile unless you do one of two things:

  1. Handle it: Wrap the call in a try-catch block.
  2. Declare it: Add a throws clause to your method's signature, passing the responsibility to whatever method called yours.

This video does an excellent job demonstrating this compile-time enforcement.

Checked vs. Unchecked Exceptions in Java Tutorial - What's The Difference?

Now let's see checked exceptions in action with the video 'Checked vs. Unchecked Exceptions in Java Tutorial' from Coding with John. This clearly shows the compiler error and the two ways to resolve it.

Watch from the beginning until 5:27. Pay close attention to the FileNotFoundException example. See how the IDE gives you a compile-time error and forces you to either add a try-catch block or a throws declaration to the method signature.

MERN-to-Java Mapping: The throws Keyword

As you saw, the throws keyword is Java's way of making potential errors part of a method's public contract. This is a major philosophical difference from TypeScript. TypeScript has no throws keyword or concept of checked exceptions; any function can throw any error at any time without warning.

This article was written for TypeScript developers and explains exactly why this difference exists, using Java's throws as the primary example. It's a perfect resource for bridging your existing knowledge.

Why TypeScript Doesn't Include a throws Keyword

The article 'Why TypeScript Doesn't Include a throws Keyword' directly compares the Java and TypeScript philosophies on error handling. It will solidify your understanding of why Java is so explicit about certain errors.

Read the sections 'Benefits of Throw Types' and 'Checked Exceptions'. Note how the Java examples show compilation errors for unhandled exceptions, something you won't see in TypeScript.



4. The Exception Hierarchy

So, how does Java know which is which? It all comes down to the class hierarchy. This diagram makes it crystal clear.

Java Exception Hierarchy Diagram
This diagram shows the exception class hierarchy in Java. Everything inherits from `Throwable`. `Error` represents serious system-level problems you usually can't recover from. `Exception` represents application-level problems. Crucially, subclasses of `RuntimeException` (in blue) are **unchecked**, while all other `Exception` subclasses (in orange) are **checked**.

The key rule to remember is:

  • If it inherits from RuntimeException, it's unchecked.
  • If it inherits from Exception but not RuntimeException, it's checked.


5. Hands-On & Debugging Exercise

Let's write some code to see this in practice. In your Main.java file, replace the contents with the following:

package com.blogplatform;

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

public class Main {

    // This method declares that it can throw a checked exception
    public static String readFirstLine(String path) throws FileNotFoundException {
        File file = new File(path);
        Scanner scanner = new Scanner(file);
        return scanner.nextLine();
    }

    // This method can throw an unchecked exception
    public static int parseAge(String ageStr) {
        return Integer.parseInt(ageStr);
    }

    public static void main(String[] args) {
        // --- Part 1: Handling a Checked Exception ---
        System.out.println("--- DEMONSTRATING CHECKED EXCEPTION ---");
        try {
            String firstLine = readFirstLine("non_existent_file.txt");
            System.out.println("First line: " + firstLine);
        } catch (FileNotFoundException e) {
            // We handle the error gracefully.
            System.out.println("Error: The file could not be found.");
            // In a real app, you would log this error.
            // e.printStackTrace(); // Uncomment to see the full stack trace
        }

        // --- Part 2: Handling an Unchecked Exception ---
        System.out.println("\n--- DEMONSTRATING UNCHECKED EXCEPTION ---");
        String badInput = "thirty";
        try {
            int age = parseAge(badInput);
            System.out.println("Age is: " + age);
        } catch (NumberFormatException e) {
            // The program would crash here if we didn't catch this.
            System.out.println("Error: '" + badInput + "' is not a valid age.");
            System.out.println("Let's examine the stack trace:");
            e.printStackTrace(); // This is essential for debugging!
        }
    }
}

Run the code. You should see the following output:

--- DEMONSTRATING CHECKED EXCEPTION ---
Error: The file could not be found.

--- DEMONSTRATING UNCHECKED EXCEPTION ---
Error: 'thirty' is not a valid age.
Let's examine the stack trace:
java.lang.NumberFormatException: For input string: "thirty"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:668)
	at java.base/java.lang.Integer.parseInt(Integer.java:786)
	at com.blogplatform.Main.parseAge(Main.java:15)
	at com.blogplatform.Main.main(Main.java:31)

Debugging-First Task: Reading the Stack Trace

The output from e.printStackTrace() is one of the most important debugging tools you have. It tells you the story of how the error happened. Let's break it down:

  1. java.lang.NumberFormatException: For input string: "thirty": This is the what. It tells you the type of exception and a message explaining the cause.
  2. at com.blogplatform.Main.main(Main.java:31): This is the where. Read from the bottom up. The error's journey started in our main method, on line 31.
  3. at com.blogplatform.Main.parseAge(Main.java:15): From main, the code called the parseAge method. The error occurred inside this method, on line 15.
  4. The lines above that (at java.base/java.lang.Integer...) show you the internal Java code that was called. Usually, you only need to focus on the lines that mention your own code (com.blogplatform...) to find the source of the problem.

Reading a stack trace is a fundamental skill. It’s your application telling you exactly where it felt pain.



Conclusion

Mastering exception handling is non-negotiable for a backend engineer. While the try-catch syntax is straightforward, the distinction between checked and unchecked exceptions is a core tenet of the Java language that promotes building resilient applications.

Key Takeaways:

  • Unchecked Exceptions (RuntimeException): Signal programming errors (NullPointerException, etc.). The compiler doesn't force you to handle them. They behave like errors in JavaScript.
  • Checked Exceptions (Exception): Signal recoverable, external problems (IOException, SQLException). The compiler forces you to either handle them with try-catch or declare them with throws.
  • The Golden Rule: A guideline from the book Effective Java is: "Use checked exceptions for recoverable conditions and runtime exceptions for programming errors."
  • Stack Traces are Your Friend: Learn to read them to quickly diagnose runtime problems.

We've now covered the essential pillars of the Java language itself. You're ready to start building.

In our next lesson, we'll dive into Maven and the pom.xml file. This is Java's build and dependency management system, the direct equivalent of npm/yarn and package.json in your MERN world. Once we have that set up, we will initialize our first Spring Boot project.