CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > User Defined Exception in Java

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor

User Defined Exception in Java

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Published: July 30, 2023 · 4 min read · 0 Comments
Share: in X
User Defined Exception in Java

In Java, exceptions are used to handle errors that occur during the execution of a program. There are many built-in exceptions in Java, but sometimes we need to create our own exceptions to handle specific errors. These exceptions are called as user defined exception in Java. This is where custom exceptions come in.

Table of Contents

  • What is user defined exception in Java?
  • Why to use user defined exceptions?
  • Create user defined exception in Java
    • 1. Choose the Exception Type
    • 2. Create a Custom Exception Class
    • 3. Throw the Custom Exception
      • Using Checked Exception:
      • Using Unchecked Exception:
    • 4. Handle the Exception
      • Handling Checked Exception (Try-Catch):
  • Best Practices
  • Key Takeaways
  • FAQs
    • Why would I need to create a user-defined exception?
    • Can user-defined exceptions be caught and handled like built-in exceptions in Java?
    • What are the benefits of using user-defined exceptions?
    • Is it possible to create a hierarchy of user-defined exceptions?
    • Are there any naming conventions or best practices for naming user-defined exceptions?

What is user defined exception in Java?

A user-defined exception is a custom exception class that we as a programmer/developer create to handle specific errors in our program. User-defined exceptions are derived from the Exception class or one of its subclasses, which is the base class for all exceptions in Java.

Why to use user defined exceptions?

There are several reasons why we might want to use user-defined exceptions in our Java programs. Following are a few of the most common reasons:

  • To provide more specific information about the error that occurred.
  • To control the flow of our program differently depending on the type of error that occurred.
  • To provide a consistent way of handling errors throughout our program.

Create user defined exception in Java

To create custom exceptions in Java, follow these steps:

1. Choose the Exception Type

  • Checked Exception: Extend Exception (must be handled or declared).
  • Unchecked Exception: Extend RuntimeException (optional handling).

2. Create a Custom Exception Class

  • Naming Convention: End the class name with Exception.
  • Constructors: Include constructors for messages and causes.

Example 1: Checked Exception

public class InsufficientFundsException extends Exception {
    // Default constructor
    public InsufficientFundsException() {
        super();
    }

    // Constructor with a message
    public InsufficientFundsException(String message) {
        super(message);
    }

    // Constructor with message and cause
    public InsufficientFundsException(String message, Throwable cause) {
        super(message, cause);
    }
}

Example 2: Unchecked Exception with Custom Field

public class InvalidAgeException extends RuntimeException {
    private final int invalidAge;

    public InvalidAgeException(int age) {
        super("Invalid age: " + age); // Message
        this.invalidAge = age;
    }

    public int getInvalidAge() {
        return invalidAge;
    }
}

3. Throw the Custom Exception

Use throw to trigger the exception in your code.

Using Checked Exception:

public class BankAccount {
    private double balance;

    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Insufficient funds. Balance: " + balance);
        }
        balance -= amount;
    }
}

Using Unchecked Exception:

public class User {
    private int age;

    public void setAge(int age) {
        if (age < 0) {
            throw new InvalidAgeException(age); // Throws unchecked exception
        }
        this.age = age;
    }
}

4. Handle the Exception

Handling Checked Exception (Try-Catch):

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        try {
            account.withdraw(100);
        } catch (InsufficientFundsException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Propagating Checked Exception (Declare throws):

public void processTransaction() throws InsufficientFundsException {
    BankAccount account = new BankAccount();
    account.withdraw(100);
}

Unchecked Exception Handling (Optional):

public class Main {
    public static void main(String[] args) {
        User user = new User();
        try {
            user.setAge(-5);
        } catch (InvalidAgeException e) {
            System.err.println(e.getMessage() + " | Invalid Value: " + e.getInvalidAge());
        }
    }
}

Best Practices

  1. Meaningful Names: Use descriptive names ending with Exception.
  2. Provide Context: Include messages and relevant data (e.g., invalidAge).
  3. Override Wisely: Override getMessage() if additional details are needed.
  4. Choose Checked/Unchecked:
    • Use checked if recovery is expected.
    • Use unchecked for programming errors (e.g., invalid arguments).

Key Takeaways

  • Extend Exception or RuntimeException.
  • Include constructors for flexibility.
  • Throw with throw and handle with try-catch or throws.

FAQs

Why would I need to create a user-defined exception?

You may want to create a user-defined exception to handle specific error scenarios that are not adequately covered by the built-in exception classes. It allows you to provide more meaningful error messages and customize the handling of those exceptions.

Can user-defined exceptions be caught and handled like built-in exceptions in Java?

Yes, user-defined exceptions can be caught and handled using try and catch blocks, just like built-in exceptions. You can catch your custom exception type and perform specific error-handling logic.

What are the benefits of using user-defined exceptions?

User-defined exceptions allow us to create a more organized and structured exception hierarchy tailored to our application’s needs. They make our code more readable, maintainable, and help convey the intent of the error.

Is it possible to create a hierarchy of user-defined exceptions?

Yes, you can create a hierarchy of user-defined exceptions by extending your custom exception classes. This hierarchy can mirror the specific error scenarios in your application.

Are there any naming conventions or best practices for naming user-defined exceptions?

It’s a good practice to end your user-defined exception class names with “Exception” to indicate their purpose clearly.
For example, “MyCustomException” or “DatabaseConnectionException.”

Related Posts:

  • Exception Handling in Java
  • Control Statements in Java
  • Compile and Run Java Program
  • Exception Handling Keywords in Java
  • Command Line Arguments in Java
  • Top 10 Common Java Errors
Tags:exceptionjavalanguage-fundamentals
Was this article helpful?
← Previous ArticleException Handling Keywords in Java
Next Article →Throwing and re-throwing an Exception in Java

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
  • Complete Guide to JaCoCo: How to Measure Java Code Coverage Accurately
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap