Java – Custom Exceptions in java

In java you have already seen some predefined classes such as NullPointerException, ArithmeticException these exceptions get triggered on certain defined conditions within their class. Meaning ? when there is a null value being computed or being used java throws an exception at run time and these can be caught using catch block.

Similarly in java you can create custom exceptions also called user defined exceptions.

You can create your own custom exceptions which can be triggered on your defined conditions using throw keyword.

Usage : Why to create Custom Exception at all ?

Sometimes you need an exception to be handled based on your set of conditions and rules in the code, in such cases you create your own custom exceptions.

Simple ! So How to create Custom Exception ?

Below we will create a custom exception class called MyCustomException

    
public class TestException{

public static void main(String args[]){
    try{
      int a=11;
      if (a>10) {
            throw new MyCustomException(a); //used throw keyword to throw Exception
      }
    }
    catch(MyCustomException e){
      System.out.println(e) ;
    }
  }

}
class MyCustomException extends Exception{

    int b;

    public MyCustomException(int a) {
      b=a;
    }

    public String toString() {
      return "The number "+b+" is out of range";
    }
}       

OUTPUT

The number 11 is out of range

Summary

So here we are, we hope now you are confident and know how to create custom Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.