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 user-defined exceptions come in.
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 a user-defined exception, we need to create a new class that extends the Exception
class or one of its subclasses. The new class should have a constructor that takes a message as a parameter. This message will be used to provide more information about the error that occurred.
Extending the Exception class
To extend the Exception
class, we need to add the following line to our class declaration:
public class MyException extends Exception {
}
Adding a custom message
The constructor for our user-defined exception class should take a message as a parameter. This message will be used to provide more information about the error that occurred. For example:
public MyException(String message) {
super(message);
}
Overriding the toString() method
The toString()
method is used to return a string representation of an object. By overriding the toString()
method in our user-defined exception class, we can customize the string that is returned. For example:
public String toString() {
return "MyException: " + getMessage();
}
Throwing a user-defined exception
The throw
keyword is used to throw an exception. When we throw an exception, the program will stop executing the current line of code and will jump to the nearest catch
block that can handle the exception. For example:
new throw MyException("Exception message goes here");
Catching a user-defined exception
To catch a user-defined exception, we use a catch
block that specifies the type of exception that we want to catch. For example:
try {
// code that might throw an exception
} catch (MyException e) {
// handle the exception
}
Example
Following is a simple example of a user-defined exception:
// Define a custom exception
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// Banking class
class BankAccount {
private double balance;
public void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance");
}
balance -= amount;
}
}
// Usage example
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(500);
try {
account.withdraw(800);
} catch (InsufficientBalanceExceptione) {
System.out.println("Error: " + e.getMessage());
}
}
}
This exception can be thrown and caught as follows:
try {
throw new InsufficientBalanceExceptione("This is an example of a user-defined exception to check Insufficient Balance in BankAaccount");
} catch (InsufficientBalanceExceptione e) {
System.out.println(e);
}
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.”