In some situation a programmer needs to create and throw his own created exception and such type of exceptions are known as User defined Exception or Custom Exceptions.
To create own exceptions we have to Extend the Exception class then only we can create custom exceptions.
Example:
class CustomExc extends Exception{
String string1;
CustomExc(String string2) {
string1=string2;
}
public String toString(){
return ("Output String = "+string1) ;
}
}
class CustomException{
public static void main(String args[]){
try{
throw new CustomExc("CustomEXC");
// It will throw user defined custom exception
}
catch(CustomExc exp){
System.out.println("This is my catch block") ;
System.out.println(exp) ;
}
}
}
Output:
This is my catch block
Output String = CustomEXC
In the above program we have created our own exception "CustomExc" and we can use it using throw keyword.
0 Comment(s)