Custom / User Defined Exception

Java Custom Exception

In your application if you are creating your own exception that is known as custom exception
By using this custom exception, you can have your own exception and your own message.

Let’s discuss how we can create custom exception in our application
Let’s assume you are working a Banking application.
          1)      User is having valid bank account
          2)      User is having valid Debit card for withdrawal the money
          3)      Same user need to have minimum balance.
          4)      Suppose bank given some rules like account holder need to maintain 500/- as minimum                       balance
          5)      If user is having less than 500/- rupees balance and user is trying to withdrawal the money then we need to give custom message like” minimum balance you can’t withdraw”
            
                 Example

package com.custom;
/**
 * @Author -- Ramu Chintha
 */

class MinimumBalance extends Exception{


MinimumBalance(String s) {
super(s);
}
}

Main Class

package com.custom;
/**
 * @Author -- Ramu Chintha
 */

public class BankMinimumBalance {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
validate(400); // User is tryting this balance to withdraw.
} catch (MinimumBalance e) {
// TODO Auto-generated catch block
System.out.println("Error is occured -->"+e);
}

}

private static void validate(int i) throws MinimumBalance{

if(i <= 500){
throw new MinimumBalance("You can't withdrawl minimum balance");
}
else{
System.out.println("you can withdram money");
}

}

}

Output:


0 comments:

Post a Comment