Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 32

Custom Exceptions in Java

In this lesson: Create user-defined checked and unchecked exceptions in Java — extend Exception, throw and catch — with output. In Hindi & English.

Why custom exceptions

Java's built-in exceptions cover general errors, but sometimes you want an error that describes your program's rules — like withdrawing more money than you have. A custom exception is your own exception class with a clear name and message, making errors easier to understand and handle.

💡 A custom exception is just a class that extends Exception (or RuntimeException).

Quick exception recap

try {
    int x = 5 / 0;             // throws ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Caught: " + e.getMessage());
}
Caught: / by zero

Exceptions are errors you can catch with try-catch. Built-in ones like ArithmeticException are useful, but custom ones let you describe your own error situations.

Creating your own exception

class InsufficientBalanceException extends Exception {
    InsufficientBalanceException(String message) {
        super(message);        // pass message to Exception
    }
}

To make a custom exception, extend Exception and add a constructor that passes a message to super. That is all it takes to have your own named error type.

Throwing and catching it

void withdraw(int balance, int amount)
        throws InsufficientBalanceException {
    if (amount > balance) {
        throw new InsufficientBalanceException("Not enough money");
    }
    System.out.println("Withdrawn: " + amount);
}
// use:
try {
    withdraw(100, 500);
} catch (InsufficientBalanceException e) {
    System.out.println("Error: " + e.getMessage());
}
Error: Not enough money

Use throw new ... to raise it, and throws in the method to declare it. The caller catches it just like any exception.

Passing a message

Passing a message to super(message) means getMessage() returns it when caught. A good message explains what went wrong — "Not enough money" is far clearer than a generic error, which helps you and other developers debug quickly.

Checked vs unchecked

  • Checked (extends Exception) — must be caught or declared with throws. Use for recoverable situations.
  • Unchecked (extends RuntimeException) — no need to declare. Use for programming errors.

Choose checked when the caller should be forced to handle the case, unchecked for bugs that should just fail.

Common mistakes

  • Not passing the message to super. Then getMessage() returns null.
  • Forgetting throws for checked exceptions. The compiler requires it or a catch.
  • Confusing throw and throws. throw raises it; throws declares it.
  • Overusing custom exceptions. Only create them for meaningful, specific situations.

Summary

  • A custom exception describes your program's own errors clearly.
  • Create it by extending Exception or RuntimeException.
  • Pass a message to super so getMessage() works.
  • Use throw to raise it and throws to declare it.
  • Checked must be handled; unchecked need not be.

Next, learn cleanup with final, finally and finalize, or organise code with Java methods.

Frequently Asked Questions

What is a custom exception in Java?
A custom exception is your own exception class that describes an error specific to your program, like InsufficientBalanceException. You create it by extending Exception (or RuntimeException), which makes error messages clearer and more meaningful.
How do I create a custom exception?
Make a class that extends Exception (checked) or RuntimeException (unchecked), and usually add a constructor that passes a message to super. Then you can throw it like any other exception.
What is the difference between throw and throws?
throw actually throws an exception object at a point in the code. throws is written in a method's signature to declare that it might throw a checked exception, warning callers to handle it.
What is the difference between checked and unchecked exceptions?
Checked exceptions (extend Exception) must be declared with throws or caught — the compiler enforces this. Unchecked exceptions (extend RuntimeException) do not require this and usually signal programming bugs.
Why use custom exceptions instead of a generic one?
A custom exception gives a clear, specific name and message for a business rule, like a negative withdrawal. This makes code easier to read and lets callers catch and handle that exact situation separately.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicAccess Modifiers Your progress: 32 / 61 (52%) · Lesson 33 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free