We can even create our own exception class in java. Our own exception class should always extend Exception class or any sub class of exception we want.
public Class MyException extends Exception{
MyException(String msg){//Then we have to make a parameterised constructor and make call to parameterised constructor of parent class.
super(msg);
}
}
We can then throw our own exception where ever we want using
throw new MyException("MyException was thrown");
or we can use it in a try catch block as well
try
{
// throw an object of user defined exception
throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}