DEV Community

Cover image for Java Exception Handling
Bellamer
Bellamer

Posted on

Java Exception Handling

The Basics

Understanding Exceptions: What Happens When Things Go Wrong?

Imagine you're playing a game, and suddenly, your character falls into a pit. What would you do? You’d probably restart the game or find a way to avoid the pit next time. In programming, something similar can happen: your code might fall into a "pit" called an exception. When that happens, the program might stop working or do something unexpected.

What Exactly is an Exception?

An exception is like a signal that something has gone wrong while your code is running. Maybe you tried to divide a number by zero (which isn’t allowed), or maybe you tried to open a file that doesn’t exist. When these problems pop up, Java raises a flag and says, "Hey! There's a problem here!"

What Happens Without Exception Handling?

If we don't handle exceptions, the program might crash, and all the progress is lost—just like when you don’t save your game and the computer suddenly turns off.

Let’s see an example:

public class BasicExample {
    public static void main(String[] args) {
        int number = 10;
        int result = number / 0; // This will cause an exception!
        System.out.println("Result: " + result); // This line will never be reached.
    }
}
Enter fullscreen mode Exit fullscreen mode

When you try to run this code, it will stop and complain, saying, "You can’t divide by zero!"

How Can We Avoid the Pit?

To avoid this problem, Java gives us something called try and catch.

  • try Block: This is where you try to do something that might cause a problem.
  • catch Block: This is where you catch the problem if it happens, so your program doesn’t crash.

Let’s Rewrite Our Example:

public class BasicExample {
    public static void main(String[] args) {
        int number = 10;

        try {
            int result = number / 0; // We know this might cause a problem.
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s what happens now:

  • The try block tries to divide by zero.
  • When Java sees the problem, it jumps to the catch block and says, "Oops! You can’t divide by zero."

Catching Different Problems

More About Catching Exceptions

Now that you know how to catch an exception, you might be wondering, "What if my code could have different kinds of problems? How do I catch them all?"

Imagine you’re trying to open a treasure chest in a game. Sometimes, the key doesn’t fit (this is one problem), and other times, the chest is empty (this is a different problem). You’d want to know exactly what went wrong, right?

Different Types of Exceptions

In Java, there are different kinds of problems, or exceptions. For example:

  • ArithmeticException: When you try to do math that doesn’t make sense, like dividing by zero.
  • NullPointerException: When you try to use something that doesn’t exist yet (like trying to open a treasure chest that isn’t there).
  • ArrayIndexOutOfBoundsException: When you try to reach into an array for something that's beyond its limits, like asking for the 11th cookie in a jar that only has 10.

Catching Multiple Exceptions

Let’s see how to catch different types of problems in your code:

public class MultipleExceptionsExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException!
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! You tried to access an index that doesn’t exist.");
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s what happens:

  • The code in the try block tries to do something that might cause a problem.
  • If it runs into an ArrayIndexOutOfBoundsException, it jumps to the first catch block.
  • If it runs into an ArithmeticException, it jumps to the second catch block.

What If I Want to Catch Any Problem?

Sometimes, you might not know what could go wrong, but you still want to catch any problem. You can use a general Exception to catch anything that goes wrong:

public class GeneralExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an ArithmeticException!
        } catch (Exception e) {
            System.out.println("Oops! Something went wrong.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This way, if anything goes wrong, the catch block will still handle it, and your program won’t crash.

Cleaning Up and Making Custom Exceptions

The finally Block

Imagine you’re playing a game and you find treasure, but whether you succeed or not, you always want to close the treasure chest when you're done. In Java, the finally block is like making sure the treasure chest is always closed, no matter what happens.

What is the finally Block?

The finally block is a piece of code that always runs, whether an exception happens or not. It’s used to clean up, like closing a file, stopping a timer, or putting away the treasure chest.

Let’s See an Example:

public class FinallyExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will cause an exception.
        } catch (ArithmeticException e) {
            System.out.println("Oops! You can’t divide by zero.");
        } finally {
            System.out.println("This will always run, no matter what.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s what happens:

  • The try block tries to do something risky.
  • The catch block catches the problem if it happens.
  • The finally block always runs, even if there’s no problem.

Making Your Own Custom Exceptions

Sometimes, the problems you face in your code are special. Maybe the game doesn’t just have treasure chests, but also magical doors that can sometimes be locked. You might want to create a special exception for when the door is locked.

Creating a Custom Exception

You can create your own exceptions by making a new class that extends Exception. Let’s create an exception called LockedDoorException:

class LockedDoorException extends Exception {
    public LockedDoorException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            openDoor(false);
        } catch (LockedDoorException e) {
            System.out.println(e.getMessage());
        }
    }

    private static void openDoor(boolean hasKey) throws LockedDoorException {
        if (!hasKey) {
            throw new LockedDoorException("The door is locked! You need a key.");
        }
        System.out.println("The door is open!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s how it works:

  • We create a new exception called LockedDoorException.
  • When we try to open the door without a key, we throw the LockedDoorException.
  • The catch block catches our custom exception and tells us what went wrong.

Summary

In this post, we’ve learned that:

  • Exceptions are problems that happen when your code is running.
  • try and catch blocks help us handle these problems, so our program doesn’t crash.

  • Different types of exceptions are like different kinds of problems.

  • We can catch multiple exceptions to handle specific problems.

  • We can also catch any exception using the general Exception type.

  • The finally block is used to clean up, and it always runs no matter what.

  • You can create custom exceptions to handle special problems in your code.

And that it! Now you’re ready to handle any problem that comes your way in your code. If you have any questions, feel free to ask!

Top comments (0)