Custom Exception in java

In Java, we create our own exception based on the programming requirement such type of exception known as a custom exception or user defined exception.

By using custom exceptions we can handle the exception in our own way and we can provide exception information based on requirement.

Example for Custom Exception


Here, our custom exception class must extend Exception or RuntimeException


public class InsufficientFunds extends RuntimeException{     
       public InsufficientFunds(String msg){
              super(msg);
       }
}


Throw keyword is used to throw custom exception


public class CustomException {
       public void payBill(double amount ){           
              if(amount<2000){                 
                     throw new InsufficientFunds("you have insufficient balance "+amount);                   
              }
              else if(amount>=2000){                  
                     System.out.println("welcome pay your bill");
              }
       }
      
       public static void main(String[] args) {       
              CustomException custex=new CustomException();
              try {
                     custex.payBill(1000);
              } catch (InsufficientFunds e) {
                     System.out.println(e);
              }
       }
}


Few points on above program


In our class better to extend RuntimeException because it is an unchecked exception and we can throw directly using throw keyword.

If we extend Exception class it is checked exception so the compiler won’t compile until we declare exception using throws or handle by try-catch.

We should handle checked exceptions otherwise compiler won’t compile the program.


public void payBill(double amount )throws InsufficientFunds{        
              if(amount<2000){                 
                     throw new InsufficientFunds("you have insufficient balance "+amount);                   
              }
              else if(amount>=2000){                  
                     System.out.println("welcome pay your bill");
              }
       }


We have methods to print exception information in Throwable class ( printStackTrace() and getMessage() )

By using super(msg); make the description to default exception handler by calling superclass methods (Throwable class).




No comments:

Post a Comment