Square CSS

Saturday, November 24, 2018

Custom Exception In Java

We can create our own custom exception in Java. This can be done by extending the Exception class of java.lang package. In other words, we need to import java.lang.Exception and extend this Exception class in our custom exception class.


Example :


First, create a class. In this case, our class is MyException which is extending the Exception class of java.lang package.



 import java.lang.Exception;
  /*extend Exception of java.lang package*/
  
  class MyException extends Exception{

          public MyException(String excStr){
           /*Create a constructor and pass string argument */

                           super(excStr);
                           /*call the parent class constructor*/

            }
  }



To apply in the code use throws and pass the string as the perimeter. Here throw new MyException("Caught Sumit!") is used to throw the exception. 



public class MyCustomException{

           public static final String DETAILS_OF_LOGGEDIN_USER= " I am Sumit";

           public static void main(String[] args){

               try{
                      if(DETAILS_OF_LOGGEDIN_USER.contains("Sumit")){
                            throw new MyException("Caught Sumit");
                       }

                }catch(MyException me){
                      System.out.println(me.getMessage());
                }  
            }
  }



The caught exception can be read by using getMessage() method of the Exception class.



In this case, the output will be the String passed in the Constructor of MyException class. So getMessage() method will print "Caught Sumit".


Refer the video tutorial:




No comments:

Post a Comment

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts