Learn Java · 6/15

Exception Handling: Expecting the Unexpected

8 min read

☕ Java Course: Exception Handling - Expecting the Unexpected

Welcome, intrepid coder, to a crucial aspect of Java programming: Exception Handling. Think of it as the art of gracefully dealing with the unexpected curveballs your program might encounter during its execution. A program that can handle errors without crashing is a robust and reliable one.

So, What's the Big Deal with Exceptions? 🤔

Imagine you're building a simple calculator application. What happens if a user tries to divide a number by zero? Without any error handling, your program would likely crash and burn, leaving the user with a frustrating experience.

This is where exception handling comes to the rescue. It provides a structured way to manage these runtime errors, preventing your application from coming to a screeching halt. When an error occurs in Java, the program "throws" an exception.


1. Understanding the Exception Hierarchy (Checked vs. Unchecked) ιε

In Java, all exceptions are objects that inherit from the Throwable class. This class has two main direct subclasses: Error and Exception.

  • Error: These represent serious problems that a reasonable application should not try to catch. Think of things like the Java Virtual Machine (JVM) running out of memory (OutOfMemoryError) or a StackOverflowError. These are generally beyond your control as a programmer.

  • Exception: This is the class you'll be working with most of the time. It represents conditions that a reasonable application might want to catch. The Exception class is further divided into two main categories:

    • Checked Exceptions: These are exceptions that are checked at compile-time. This means the compiler forces you to handle them explicitly. If a method can throw a checked exception, it must either handle it internally or declare that it can throw that exception using the throws keyword in its signature. A classic example is IOException, which can occur when working with files.

    • Unchecked Exceptions (Runtime Exceptions): These exceptions are not checked at compile-time. They typically represent programming errors, such as logical flaws in your code. Examples include NullPointerException (trying to use an object that is null) and ArrayIndexOutOfBoundsException (accessing an array with an invalid index). Unchecked exceptions extend the RuntimeException class.

A simple way to remember:

  • Checked: "Check this out! You must deal with me." - The Compiler
  • Unchecked: "I'm a result of your own doing. You should fix your code, but I won't force you." - The Runtime Environment

Here's a simplified view of the hierarchy:

livescript
                  Object
                    |
                 Throwable
                  /   \
               Error   Exception
                       |
                  RuntimeException
                  /    |    \
   NullPointerException  ...   ...

Industry Practice: While you are forced to handle checked exceptions, it's a good practice to write code that avoids unchecked exceptions in the first place. For instance, before accessing an array element, check if the index is within the valid range.


2. Try, Catch, and Finally: Safely Handling Runtime Errors 🛡️

The try-catch block is your primary tool for handling exceptions.

The Problem: You have a piece of code that might throw an exception, and you don't want your program to crash.

The Solution: You wrap the potentially problematic code in a try block and provide a catch block to handle the exception if it occurs.

Syntax:

java
try {
  // Code that might throw an exception
} catch (ExceptionType e) {
  // Code to handle the exception
}

Example: Let's go back to our calculator and handle the division by zero scenario.

java
public class Calculator {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will throw an ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can't divide by zero. That's a math no-no. 🙅");
        }
        System.out.println("Program continues...");
    }
}

What's happening here?

  1. The code inside the try block is executed.
  2. When 10 / 0 is attempted, the JVM throws an ArithmeticException.
  3. The catch block is specifically looking for an ArithmeticException. Since that's what was thrown, the code inside the catch block is executed.
  4. Crucially, the program doesn't crash. The line "Program continues..." will be printed.

The finally Block: The Unsung Hero 🦸

There are times when you need a piece of code to run regardless of whether an exception was thrown or not. This is where the finally block comes in. It's often used for cleanup operations, like closing files or network connections.

The finally block is executed after the try block, and after a catch block if an exception was caught.

Example:

java
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

public class FileManager {
    public static void main(String[] args) {
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new File("myFile.txt"));
            writer.println("Hello, World!");
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        } finally {
            if (writer != null) {
                System.out.println("Closing the writer.");
                writer.close();
            }
        }
    }
}

In this example, even if the file can't be found and a FileNotFoundException is thrown, the finally block will still execute to ensure the writer is closed, preventing resource leaks.

Interesting Fact: A try block can be followed by a catch block, a finally block, or both. You can even have a try-finally block without a catch block.


3. Throw and Throws: Passing the Buck โย

Sometimes, a method itself doesn't know how to handle an exception. In such cases, it can "pass the buck" to the method that called it. This is done using the throw and throws keywords.

The throws Keyword

The throws keyword is used in a method's signature to declare that it might throw one or more exceptions. This essentially serves as a warning to any method that calls it, saying, "Hey, if you call me, be prepared to handle these types of exceptions!"

Syntax:

java
public void myMethod() throws ExceptionType1, ExceptionType2 {
    // Code that might throw exceptions
}

Example:

java
import java.io.IOException;

public class FileReader {
    public void readFile() throws IOException {
        // Code that reads a file and could throw an IOException
        throw new IOException("An error occurred while reading the file.");
    }
}

public class Main {
    public static void main(String[] args) {
        FileReader reader = new FileReader();
        try {
            reader.readFile();
        } catch (IOException e) {
            System.err.println("Caught the exception: " + e.getMessage());
        }
    }
}

Here, the readFile method declares that it can throw an IOException. The main method, which calls readFile, is then responsible for handling that exception with a try-catch block.

The throw Keyword

The throw keyword is used to explicitly throw an exception from within a method or block of code. You can throw either a new instance of an exception or an existing one.

Syntax:

java
throw new ExceptionType("An optional message");

When to use throw? You use throw when you detect a specific error condition in your code and want to signal it as an exception.

Example:

java
public class BankAccount {
    private double balance;

    public void withdraw(double amount) {
        if (amount > balance) {
            throw new IllegalArgumentException("Insufficient funds");
        }
        balance -= amount;
    }
}

In this example, if someone tries to withdraw more money than they have, we explicitly throw an IllegalArgumentException.

Key Difference:

  • throws: A declaration in the method signature about what exceptions might be thrown.
  • throw: An action of actually throwing an exception.

4. Creating Custom Exceptions for Your Domain 🧑‍🔧

While Java provides a rich set of built-in exception classes, sometimes you need to create your own to represent specific error conditions in your application. This makes your code more readable and easier to debug.

The Problem: You have an application-specific error that isn't well-represented by any of the standard Java exceptions.

The Solution: Create your own custom exception class.

How to do it?

  1. Create a new class that extends either Exception (for a checked exception) or RuntimeException (for an unchecked exception).
  2. It's a good practice to provide a constructor that takes a String message.

Example: A Custom Checked Exception

Let's imagine you're building a user registration system where usernames must be unique.

java
// 1. Create the custom exception class
public class UsernameAlreadyExistsException extends Exception {
    public UsernameAlreadyExistsException(String message) {
        super(message);
    }
}

// 2. Use the custom exception in your code
public class UserService {
    public void registerUser(String username) throws UsernameAlreadyExistsException {
        // Logic to check if the username exists in the database
        boolean usernameExists = true; // For demonstration purposes

        if (usernameExists) {
            throw new UsernameAlreadyExistsException("Username '" + username + "' is already taken.");
        }
        // Proceed with user registration
    }
}

// 3. Handle the custom exception
public class Main {
    public static void main(String[] args) {
        UserService userService = new UserService();
        try {
            userService.registerUser("john.doe");
        } catch (UsernameAlreadyExistsException e) {
            System.err.println("Registration failed: " + e.getMessage());
        }
    }
}

By creating a UsernameAlreadyExistsException, your code becomes much clearer about the specific error that occurred, making it easier for other developers to understand and handle.


📚 References for Extra Reading

Challenge

Your task is to implement a simple banking system that uses custom exceptions to handle invalid transactions.

  1. Define a new custom checked exception named InsufficientFundsException. It must extend the Exception class and have a constructor that accepts a String message.
  2. Create a BankAccount class with a private double field named balance and a public constructor to initialize it.
  3. Inside the BankAccount class, create a public method public void withdraw(double amount) throws InsufficientFundsException. This method should:
    • First, check if the amount is positive. If amount is less than or equal to zero, throw a new IllegalArgumentException with the message "Withdrawal amount must be positive.".
    • Next, check if the amount exceeds the current balance. If it does, throw a new InsufficientFundsException with the message "Insufficient funds for this withdrawal.".
    • If the transaction is valid, subtract the amount from the balance.
  4. In the Main class, inside the main method, create an instance of BankAccount with an initial balance of 500.0.
  5. Use a try-catch-finally block to manage a call to the withdraw method. In the try block, attempt to withdraw 600.0.
  6. Provide two separate catch blocks. The first should catch InsufficientFundsException, and the second should catch IllegalArgumentException. Each block should print the message from the caught exception.
  7. The finally block must print the string "Transaction processing complete.".

Expected result

When your code is executed, it should handle the exception thrown by the withdraw method. The output should consist of two lines:

  1. The message from the InsufficientFundsException that was caught.
  2. The message from the finally block.

For example:

erlang
Insufficient funds for this withdrawal.
Transaction processing complete.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.