CodeGym /Courses /JAVA 25 SELF /Creating custom exceptions

Creating custom exceptions

JAVA 25 SELF
Level 24, Lesson 1
Available

1. Introduction

The Java standard library already includes many exceptions: NullPointerException, IllegalArgumentException, IOException, and others. But sometimes the standard exceptions aren’t enough to clearly and precisely describe the error that occurred in your program.

Real-world example:
You’re building a banking app. A user tries to withdraw more money than the account balance. You could throw IllegalArgumentException. But it’s much clearer to introduce your own exception, for example, InsufficientFundsException. Then it’s immediately obvious from the code what happened.

Custom exceptions are a solid way to tailor your application. They let you fine-tune how you deal with problems, and their names (if chosen sensibly!) immediately communicate what happened. They are also self-documenting: methods with throws MyException in the signature immediately tell you what errors can occur. And you can always add additional fields (for example, the balance, the transaction amount, etc.).

2. How to create your own exception?

It’s straightforward: create a new class that extends one of the standard exception classes.

  • For checked exceptions — extend Exception.
  • For unchecked — extend RuntimeException.

Example: checked exception

public class InvalidCredentialsException extends Exception {
    public InvalidCredentialsException(String message) {
        super(message); // Pass the message to the superclass
    }
}

Now you can throw this exception in your code:

if (!login.equals("admin") || !password.equals("1234")) {
    throw new InvalidCredentialsException("Invalid username or password");
}

Example: unchecked exception

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

When to use checked vs. unchecked?

  • Checked — when the error is expected and can be handled (for example, a validation error, a missing file, invalid user data).
  • Unchecked — when the error is due to a bug in the program’s logic (for example, division by zero, invariant violation).

3. Constructors: making an exception informative

Typically, your exception class implements at least one constructor with the String message parameter. But often you add others as well:

public class ScoreLimitExceededException extends Exception {
    public ScoreLimitExceededException() {
        super();
    }
    public ScoreLimitExceededException(String message) {
        super(message);
    }
    public ScoreLimitExceededException(String message, Throwable cause) {
        super(message, cause);
    }
    public ScoreLimitExceededException(Throwable cause) {
        super(cause);
    }
}

Explanation:

  • message — a textual description of the error.
  • cause — the cause (another exception) if you want to wrap one error in another.

Tip: if you’re not sure which constructors you need, add at least the one that takes a string.

4. Using custom exceptions in code

Let’s look at an example: we have a user, the user has points, and you can’t add more than 100.

public class User {
    private String name;
    private int score;

    public User(String name) {
        this.name = name;
        this.score = 0;
    }

    public void addScore(int points) throws ScoreLimitExceededException {
        if (score + points > 100) {
            throw new ScoreLimitExceededException("Score limit exceeded! Attempted to add: " + points);
        }
        this.score += points;
    }
}

Exception class:

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

Handling:

try {
    user.addScore(60);
    user.addScore(50); // An exception will be thrown here!
} catch (ScoreLimitExceededException e) {
    System.out.println("Error: " + e.getMessage());
}

Output:

Error: Score limit exceeded! Attempted to add: 50

You might be wondering: what if, instead of throwing an exception, we simply use an if condition and, for example, return false or some other special value to indicate that the operation failed? For example:

public boolean addScore(int points) {
    if (score + points > 100) {
        return false; // Or throw some RuntimeException if you don't want to handle it
    }
    this.score += points;
    return true;
}

Although this approach may seem simpler, it has drawbacks when it comes to serious errors or violations of application logic.

First, returning false or another value to indicate an error forces the calling code to always check the return value. If a developer forgets to do this, the error can go unnoticed, which leads to unpredictable program behavior. Exceptions, by contrast, force handling (for checked exceptions) or at least clearly signal a problem if they are not caught.

Second, exceptions convey the semantics of the error more explicitly. Returning false can mean anything: “failed”, “not applicable”, “unavailable”. The exception ScoreLimitExceededException clearly and unambiguously states: “the score limit has been exceeded”. This improves readability and maintainability.

Third, exceptions allow you to centralize error handling. Instead of scattering if-checks throughout the code wherever addScore is called, you can catch the exception in one place and take an appropriate action: show a message to the user, write to the log, or roll back a transaction.

Finally, for issues like exceeding a limit, this really is an exceptional situation (hence the name). The normal execution flow assumes that points will be added successfully. If that’s not the case, it’s a violation of business logic or object invariants—an ideal scenario for using exceptions.

5. Adding custom fields to exceptions

Sometimes it’s useful to add extra data to your exception that will help handle the error.

Example:

public class ScoreLimitExceededException extends Exception {
    private int currentScore;
    private int attemptedAdd;

    public ScoreLimitExceededException(String message, int currentScore, int attemptedAdd) {
        super(message);
        this.currentScore = currentScore;
        this.attemptedAdd = attemptedAdd;
    }

    public int getCurrentScore() { 
        return currentScore; 
    }
    public int getAttemptedAdd() { 
        return attemptedAdd; 
    }
}

Usage:

if (score + points > 100) {
    throw new ScoreLimitExceededException(
        "Score limit exceeded!",
        this.score,
        points
    );
}

6. Useful nuances

How to name your exceptions?

In Java, it’s conventional to name custom exceptions with the Exception suffix: InvalidUserInputException, InsufficientFundsException, ScoreLimitExceededException.

Don’t name your exceptions simply Error or Warning—this can mislead other developers (and even you in a couple of weeks).

Where and when should you throw your exceptions?

  • During user input validation (for example, empty name, negative age).
  • On business rule violations (for example, exceeding a limit, attempting to withdraw more money than the account balance).
  • On errors when working with external services (for example, service unavailable, timeout exceeded).

7. Common mistakes when creating custom exceptions

Mistake No. 1: Extending the wrong class.
Extend Exception (or RuntimeException), not Throwable or Error.

Mistake No. 2: No constructor with a message.
Without a constructor that takes a string (String message), your exceptions will be mute and harder to debug.

Mistake No. 3: Using standard exceptions for business logic.
Don’t throw NullPointerException or IllegalArgumentException where you need your own “meaningful” exception.

Mistake No. 4: Overusing custom exceptions.
Don’t create a separate exception class for every little thing. If the error isn’t unique to your domain, use standard exceptions.

Mistake No. 5: Missing serialization (rare, but happens).
If your exception will be sent over the network or persisted, consider implements Serializable. However, for simple applications this isn’t critical.

1
Task
JAVA 25 SELF, level 24, lesson 1
Locked
Game Gatekeeper: Player Score Check
Game Gatekeeper: Player Score Check
1
Task
JAVA 25 SELF, level 24, lesson 1
Locked
Password Fortress: Protecting User Data
Password Fortress: Protecting User Data
1
Task
JAVA 25 SELF, level 24, lesson 1
Locked
Age verification at the amusement park: Flexible error messages
Age verification at the amusement park: Flexible error messages
1
Task
JAVA 25 SELF, level 24, lesson 1
Locked
Magical Artifacts Warehouse Management: Precise Overflow Details
Magical Artifacts Warehouse Management: Precise Overflow Details
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION