While defining an user defined exception, we need to take care of the following aspects:
- The user defined exception class should extend from Exception class.
- The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.
Let us see a simple example to learn how to define and make use of user defined exceptions.
class NoSufficientFundException extends Exception { int amt; public NoSufficientFundException(int amt) { this.amt = amt; } public String toString() { return "You can't withdraw the amt:" + amt; } } class Bank { void withdraw(int accno, int balance, int amt) throws NoSufficientFundException { if (balance - amt >= 500) { balance -= amt; System.out.println("Successful withdrawal.Balance:" + balance); } else { throw new NoSufficientFundException(amt); } } } public class TestUserDefinedException { public static void main(String[] args) { try { new Bank().withdraw(1222345, 1000, 1000); } catch (NoSufficientFundException e) { e.printStackTrace(); } } }
The output is:
You can't withdraw the amt:1000
at Bank.withdraw(TestUserDefinedException.java:24)
at TestUserDefinedException.main(TestUserDefinedException.java:34)
In the above example, the withdraw method throws the user defined exception NoSufficientFundException if the amount can't withdraw due to insufficient balance.
No comments:
Post a Comment