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.
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)
at com.test.Demo.main(Test.java:9)
Ex:
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