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.
First, create a class. In this case, our class is MyException which is extending the Exception class of java.lang package.
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.
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".
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*/ } } |
public class MyCustomException{ 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.
No comments:
Post a Comment