User-defined exceptions in Java are used to handle the application-specific error conditions. Here application-specific error conditions are bound to a specific application those are not generic for all the applications.
The guys implemented the Java API, provide us extreme Exception handling mechanism which was generic for all the Java-based applications. In the previous tutorials, we have discussed what is Exceptions and top 10 Exceptions in Java. Now we are going to discuss the importance of user-defined exceptions.
User Defined Exceptions Scenario
The best scenario, when we talk about the user defined exceptions are banking domain applications. In any banking application, the major modules are deposits and withdrawals. When performing a withdrawal from a bank account, it is required to validate the minimum balance in the account. To validate this requirement Java didn’t provide any specific exception class. Hence to handle this requirement, a user-defined exception MinimumAccountBalance may be created.
The user defined exceptions are generated using the throw statement and handle them as normal exceptions.
If necessary, we can write our own user defined exceptions and throw and handle them. We can create the user defined exceptions by extending the Exception class.
Syntax:
class MinimumAccountBalance extends Exception{
}
User Defined Exceptions Example
import java.util.Scanner;
class MinimumAccountBalance extends Exception {
String message;
public MinimumAccountBalance(String message) {
this.message = message;
}
@Override
public String toString() {
return message;
}
}
public class UserDefinedException {
static double current_balance = 100;
public static void main(String[] args) throws MinimumAccountBalance {
Scanner s = new Scanner(System.in);
System.out.println("Enter amount to withdrawal");
int n = s.nextInt();
try {
if (current_balance < n) {
throw new MinimumAccountBalance("Insufficient funds ! your Current balance is " + current_balance);
} else {
System.out.println("Please Take The Money : " + n);
}
} catch (MinimumAccountBalance mab) {
mab.printStackTrace();
}
}
}
Output:
Case I:
Enter amount to withdrawal
200
Insufficient funds ! your Current balance is 100.0
Case II:
Enter amount to withdrawal
90
Please Take The Money : 90
Happy Learning 🙂