Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

User Defined Exception in Java

Last Updated on July 20, 2023 by Mayank Dham

An exception is an event that occurs during program execution and disrupts the normal flow of the program’s instructions. Exceptions are used in programming to handle errors and other unusual events. They are typically generated when a runtime error occurs, such as a division by zero or an out-of-bounds array access. An exception handler can catch and handle the exception in the code, allowing the program to continue running instead of crashing or producing an incorrect result. In Java, a user defined exception is a powerful tool for dealing with specific requirements and scenarios. They enable programmers to provide more descriptive error messages and manage exceptions more effectively and efficiently.

What are User-Defined Exceptions?

User-defined exceptions are custom exceptions that a programmer can add to their code to deal with specific error conditions or situations. These exceptions are derived from the base exception class and allow the programmer to customize the exception-handling process to meet their specific requirements. User-defined exceptions are used to indicate errors that are specific to the application being developed, and they are frequently used in code to provide a higher level of abstraction and readability.

For example, a programmer may create a custom exception for a bank account class that checks if a withdrawal would result in a negative balance. If a withdrawal would cause a negative balance, the custom exception is thrown and can be caught and handled by the code. This allows the programmer to provide more meaningful error messages and handling of specific error conditions in the code, rather than relying on generic exceptions.

Why use User-defined Exceptions?

These are the following uses of user defined exception in java or in any language

  • User defined exception in java are used to provide a higher level of abstraction and readability in the code by encapsulating error-handling logic in specific parts of the code. They offer several benefits, such as:
  • Improved readability and maintainability: User-defined exceptions make it easier to understand the code and improve its maintainability by providing meaningful error messages and handling specific error conditions.
  • Better error handling: Custom exceptions can be used to handle specific errors in a more meaningful and appropriate manner, leading to better error handling and improved reliability of the code.
  • Modularity: User-defined exceptions can be used to create modular code, making it easier to manage complex and large applications.
  • Reusability: Custom exceptions can be reused across different parts of the code, making it easier to implement error handling in a consistent manner.
  • Better error reporting: User-defined exceptions can provide more information about the error, making it easier to diagnose and fix the problem.

How to Implement User-defined Exception in Java?

To implement a user-defined exception in Java, follow these steps:

  • Create a custom exception class that extends the base exception class (java.lang.Exception).
  • Define the constructor for the custom exception class. The constructor can accept parameters to provide more information about the error.
  • Override the toString() method to provide a custom error message.
  • Use the "throw" keyword to throw an instance of the custom exception when the error condition occurs.
  • Use a "try-catch" block to catch the exception and handle it appropriately.

Here is an example implementation of a user-defined exception class:

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

class BankAccount {
    private double balance;

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

    public void withdraw(double amount) throws NegativeBalanceException {
        if (balance - amount < 0) {
            throw new NegativeBalanceException("Insufficient funds to withdraw " + amount + " dollars.");
        } else {
            balance -= amount;
        }
    }
}

 class Main {
    public static void main(String[] args) {
        BankAccount ba = new BankAccount(100);

        try {
            ba.withdraw(200);
        } catch (NegativeBalanceException ex) {
            System.out.println(ex.getMessage());
        }

        System.out.println("Remaining balance: " + ba.getBalance());
    }
}

Output:

Insufficient funds to withdraw 200.0 dollars.
Remaining balance: 100.0

Explanation:
In this example, we have created a custom exception class NegativeBalanceException, which extends Exception, as well as a class BankAccount, which includes a withdrawal method. If the balance is less than the amount withdrawn, an instance of NegativeBalanceException with an error message is thrown. The exception is then caught and the error message is printed in the main method.

Examples of User Defined Exception in Java

1) User Defined exception in java for Validating Login Credentials
Here is an example of a user-defined exception class to validate login credentials:

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

class Login {
    private String username;
    private String password;

    public Login(String username, String password) throws InvalidCredentialsException {
        if (username == null || username.isEmpty()) {
            throw new InvalidCredentialsException("Username cannot be null or empty.");
        }

        if (password == null || password.isEmpty()) {
            throw new InvalidCredentialsException("Password cannot be null or empty.");
        }

        this.username = username;
        this.password = password;
    }

    public boolean validate() {
        // Check the username and password against a database or other sources
        return true;
    }
}

 class Main {
    public static void main(String[] args) {
        try {
            Login login = new Login("", "password");
        } catch (InvalidCredentialsException ex) {
            System.out.println(ex.getMessage());
        }

        try {
            Login login = new Login("username", "");
        } catch (InvalidCredentialsException ex) {
            System.out.println(ex.getMessage());
        }

        try {
            Login login = new Login("username", "password");
            if (login.validate()) {
                System.out.println("Login successful.");
            } else {
                System.out.println("Login failed.");
            }
        } catch (InvalidCredentialsException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Output:

Username cannot be null or empty.
Password cannot be null or empty.
Login successful.

Explanation:
In this example, the Login class has a custom exception class InvalidCredentialsException to validate the username and password of the user. If the username or password is empty or null, an instance of InvalidCredentialsException is thrown with an error message. The exception is then caught in the main method and its error message is printed.

2) User Defined exception in java for Validity of an Entity
Here is an example of a user-defined exception class to check the validity of an entity:

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

class Entity {
    private String name;
    private int age;

    public Entity(String name, int age) throws InvalidEntityException {
        if (name == null || name.isEmpty()) {
            throw new InvalidEntityException("Name cannot be null or empty.");
        }

        if (age < 0) {
            throw new InvalidEntityException("Age cannot be negative.");
        }

        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class Main {
    public static void main(String[] args) {
        try {
            Entity e = new Entity("John", -30);
        } catch (InvalidEntityException ex) {
            System.out.println(ex.getMessage());
        }

        try {
            Entity e = new Entity("", 25);
        } catch (InvalidEntityException ex) {
            System.out.println(ex.getMessage());
        }

        try {
            Entity e = new Entity("Jane", 30);
            System.out.println("Name: " + e.getName());
            System.out.println("Age: " + e.getAge());
        } catch (InvalidEntityException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Output:

Age cannot be negative.
Name cannot be null or empty.
Name: Jane
Age: 30

Explanation:
In this example, the Entity class has a custom exception class InvalidEntityException to validate the name and age of the entity. If the name is empty or null or if the age is negative, an instance of InvalidEntityException is thrown with an error message. The exception is then caught in the main method and its error message is printed.

3) User Defined exception in java for Validating the age of user
Here is an example of a user-defined exception class to validate the age of a user:

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

class User {
    private int age;

    public User(int age) throws InvalidAgeException {
        if (age < 0) {
            throw new InvalidAgeException("Age cannot be negative.");
        }

        if (age > 150) {
            throw new InvalidAgeException("Age is too high.");
        }

        this.age = age;
    }
}

class Main {
    public static void main(String[] args) {
        try {
            User user = new User(-1);
        } catch (InvalidAgeException ex) {
            System.out.println(ex.getMessage());
        }

        try {
            User user = new User(151);
        } catch (InvalidAgeException ex) {
            System.out.println(ex.getMessage());
        }

        try {
            User user = new User(30);
            System.out.println("Age is valid.");
        } catch (InvalidAgeException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Output:

Age cannot be negative.
Age is too high.
Age is valid.

Explanation:
In this example, the User class has a custom exception class InvalidAgeException to validate the age of a user. If the age of the user is negative or too high, an instance of InvalidAgeException is thrown with an error message. The exception is then caught in the main method and its error message is printed.

Conclusion
User-defined exceptions are useful in software development because they allow programmers to make their code more readable, maintainable, and error-free. They can also be used to make code more modular by encapsulating error-handling logic in specific sections of code. The use of user-defined exceptions helps to improve the quality of the code and makes it easier to understand and maintain, even for large and complex applications.

Frequently Asked Questions(FAQ):

Here are some frequently asked questions about User defined exception in java

Q1. What is the difference between checked and unchecked exceptions in Java?
Checked exceptions in Java are exceptions that must be explicitly caught or declared in the method that throws them, whereas unchecked exceptions do not. Unless they are derived from the base unchecked exception class (java.lang.RuntimeException), user-defined exceptions are typically treated as checked exceptions.

Q2. What is the purpose of user defined exceptions in Java?
In Java, user defined exceptions allow programmers to create their own custom exception classes, which provide more meaningful error messages and error-handling capabilities than built-in exceptions.

Q3. How do you create a user defined exception in Java?
In Java, to create a user-defined exception, you must first create a custom exception class that extends the base exception class (java.lang.Exception). The custom exception class can have its own constructor and methods, which enables the programmer to provide more meaningful error messages and handle specific error conditions.

Q4. How do you throw a user defined exception in Java?
In Java, you use the "throw" keyword followed by an instance of the custom exception class to throw a user-defined exception. As an example: new NegativeBalanceException("Inadequate funds.");

Leave a Reply

Your email address will not be published. Required fields are marked *