DEV Community

Cover image for How Do You Create a Custom Exception in Java?
Gowtham Kalyan
Gowtham Kalyan

Posted on

How Do You Create a Custom Exception in Java?

1. Introduction

In Java, a custom exception is a user-defined exception created to handle specific business logic errors.

Instead of using only built-in exceptions, you can define your own exception to make your code:

  • More readable
  • More meaningful
  • Easier to debug

2. Why Do We Need Custom Exceptions?

Explanation

Sometimes built-in exceptions are not enough. For example:

  • Invalid user age
  • Insufficient balance
  • Invalid input in business logic

In such cases, custom exceptions provide clear and domain-specific error messages.


3. Steps to Create Custom Exception

Step 1: Extend Exception Class

  • For checked exception → extend Exception
  • For unchecked exception → extend RuntimeException

4. Example (Checked Custom Exception)

// Step 1: Create custom exception
class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

// Step 2: Use custom exception
public class CustomExceptionExample {
    public static void main(String[] args) {
        int age = 16;

        try {
            if (age < 18) {
                throw new InvalidAgeException("Age must be 18 or above");
            }
            System.out.println("Eligible");
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Explanation of Code

  • InvalidAgeException extends Exception → Checked exception
  • Constructor passes message to parent class
  • throw new InvalidAgeException(...) → explicitly throws exception
  • catch block handles it

Output:

Age must be 18 or above
Enter fullscreen mode Exit fullscreen mode

6. Example (Unchecked Custom Exception)

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

public class UncheckedCustomException {
    public static void main(String[] args) {
        int amount = -100;

        if (amount < 0) {
            throw new InvalidAmountException("Amount cannot be negative");
        }

        System.out.println("Valid amount");
    }
}
Enter fullscreen mode Exit fullscreen mode

7. Explanation

  • Extends RuntimeException → Unchecked exception
  • No need for try-catch (optional)
  • Used for programming or validation errors

8. Key Points

  • Custom exceptions improve code clarity
  • Can be checked or unchecked
  • Use meaningful names (e.g., InvalidAgeException)
  • Always provide a clear message

9. Best Practices

  • Use checked exceptions for recoverable conditions
  • Use unchecked exceptions for logic errors
  • Keep exception classes simple and focused
  • Add constructors for flexibility

10. Summary

  • Custom exceptions = user-defined exceptions
  • Created by extending Exception or RuntimeException
  • Used for handling specific application scenarios
  • Improve readability and maintainability

Java Full Stack Developer Roadmap

To master exception handling and advanced Java concepts:

👉 https://www.ashokit.in/java-full-stack-developer-roadmap


Promotional Content

Want to master Java Exception Handling including Custom Exceptions?

Best Core JAVA Online Training in ameerpet

Top comments (0)