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?
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
- Meaningful Names: Use descriptive names ending with
Exception
. - Provide Context: Include messages and relevant data (e.g.,
invalidAge
). - Override Wisely: Override
getMessage()
if additional details are needed. - Choose Checked/Unchecked:
- Use checked if recovery is expected.
- Use unchecked for programming errors (e.g., invalid arguments).
Key Takeaways
- Extend
Exception
orRuntimeException
. - Include constructors for flexibility.
- Throw with
throw
and handle withtry-catch
orthrows
.
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.”