1.

Create a custom exception in Java

Answer»

Custom Exceptions are nothing but user defined exceptions. Java custom exceptions are used to make and modify the exception according to the requirements of the user.

Before CREATING a custom exception, let us look at its prerequisites

  • All exceptions that are created must be a subclass of Throwable CLASS
  • Use the extends keyword and EXTEND the Exception class
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

Let us now create a parent custom exception which generates an exception if a number is not divisible by 3:

class CustomException extends Exception {    CustomException(String errormsg)  {    super(errormsg);    } }   public class Example {     static void validate(INT num)throws CustomException  {     if(num%3!=0)        throw new CustomException("Not divisible by 3");       else      System.out.println("Divisible by 3");     }   public static void main(String args[])   {      try      {      validate(10);        }      catch(Exception e)      {       System.out.println("Exception caught: "+e);      }      System.out.println("Outside the try-catch block");    } }  

The output for the above program is as follows:

$javac Example.java $java Example Exception caught: CustomException: Not divisible by 3 Outside the try-catch block


Discussion

No Comment Found