User defined Custom Exception in Java

 User defined Custom Exception in Java

Sometime to meet our programming requirement we can define our own exceptions, such types are exception are called customized or user define exception.
 
Ex:
  • ToYoungException 
  • ToOldException 
  • InSufficientFundException
  • RakaIsGoodBoyException 
 
Create User define exception:
  • For creating own exception class, must be extends Throwable class or its child class.
  •  It is highly recommended to define customized exception as unchecked. Means we have to extends RuntimeException but not Exception or Throwable.
 Ex:
 
class Test extends Throwable
{
        Test(String s)
       {
          super(s);
       }
}  
 
class Demo
{
   public static void main(String[] agrs)
   {
       throw new Test(" Custom exception by Raka");
   }
}
 
O/P:  Exception in thread "main" com.test.Demo: Custom exception by Raka
    at com.test.Demo.main(Test.java:9)

 
 Ex:
Custom exceptionin java

Custom exception in java

 Note: 

  • throw keyword is best suitable for user define or custom exception but not for pre-defined exception.
  • It is highly recommended to define customized exception as unchecked. Means we have to extends RuntimeException but not Exception 
 
RAKESH RAKA

I am Rakesh Raka, senior software engineer (JAVA) in Sopra Steria.

Post a Comment (0)
Previous Post Next Post