Java - Custom Exception

Hello there, future Java wizards! Today, we're going to dive into the magical world of Custom Exceptions in Java. Don't worry if you're new to programming; I'll guide you through this journey step by step, just like I've done for countless students over my years of teaching. So, grab your virtual wands (keyboards), and let's cast some exception spells!

Java - Custom Exception

What Are Exceptions?

Before we delve into custom exceptions, let's quickly recap what exceptions are in Java. Imagine you're cooking a delicious meal, but suddenly you realize you're out of a crucial ingredient. That's similar to an exception in programming – it's an unexpected event that disrupts the normal flow of your program.

Java provides many built-in exceptions, but sometimes, we need to create our own. That's where custom exceptions come in handy!

Need for Java Custom Exceptions

You might wonder, "Why do we need custom exceptions when Java already has so many?" Well, let me explain with a fun analogy.

Imagine you're playing a game of "Catch the Exception." Java's built-in exceptions are like standard balls, but sometimes you need a special ball that fits perfectly in your hand. That's what custom exceptions are – tailored to fit your specific program needs!

Custom exceptions allow us to:

  1. Create more meaningful error messages
  2. Group related exceptions
  3. Add additional properties to exceptions

Creating a Custom Exception in Java

Now, let's roll up our sleeves and create our first custom exception! It's easier than you might think.

Here's the basic structure:

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

Let's break this down:

  1. We create a new class and name it (in this case, MyCustomException).
  2. We extend the Exception class (or RuntimeException if we want an unchecked exception).
  3. We create a constructor that takes a String message.
  4. We call the superclass constructor using super(message).

Java Custom Exception Example

Let's create a more practical example. Imagine we're creating a banking application, and we want to create a custom exception for when someone tries to withdraw more money than they have in their account.

public class InsufficientFundsException extends Exception {
    private double amount;

    public InsufficientFundsException(double amount) {
        super("Sorry, insufficient funds. You need " + amount + " more.");
        this.amount = amount;
    }

    public double getAmount() {
        return amount;
    }
}

Now, let's see how we can use this exception in our BankAccount class:

public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            double needs = amount - balance;
            throw new InsufficientFundsException(needs);
        }
        balance -= amount;
        System.out.println("Withdrawal successful. New balance: " + balance);
    }
}

And here's how we might use it in our main program:

public class BankingApp {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(100);
        try {
            account.withdraw(150);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage());
            System.out.println("You need to deposit at least: " + e.getAmount());
        }
    }
}

When you run this program, it will output:

Sorry, insufficient funds. You need 50.0 more.
You need to deposit at least: 50.0

Isn't that neat? We've created a custom exception that not only tells us there's an error but also provides useful information about how much more money is needed!

Example: Creating a Custom Class by Extending RuntimeException

Sometimes, you might want to create an unchecked exception. In that case, you'd extend RuntimeException instead of Exception. Here's an example:

public class InvalidAgeException extends RuntimeException {
    public InvalidAgeException(String message) {
        super(message);
    }
}

And here's how you might use it:

public class Person {
    private int age;

    public void setAge(int age) {
        if (age < 0 || age > 150) {
            throw new InvalidAgeException("Age must be between 0 and 150");
        }
        this.age = age;
    }
}

In this case, we don't need to declare the exception in the method signature or catch it explicitly (although it's often a good idea to do so).

Conclusion

And there you have it, folks! You've just learned how to create and use custom exceptions in Java. Remember, custom exceptions are like your personal Swiss Army knife in the coding world – they help you handle errors more effectively and make your code more readable and maintainable.

As you continue your Java journey, you'll find more and more uses for custom exceptions. They're a powerful tool in your programming toolkit, helping you create robust and user-friendly applications.

Keep practicing, keep coding, and most importantly, have fun! After all, as I always tell my students, programming is like magic – you're creating something out of nothing. And now, you can even control how your program behaves when things go wrong. How cool is that?

Until next time, happy coding!

Credits: Image by storyset