how to create custom checked exception –
We can create our own exceptions by extending ‘Exception’ class. Below example will show you how to create custom exception by extending Exception class.
It is a checked exception, so you must have to catch it declare as throws clause.
if you comment out try/catch in MyCustomExceptionTest class where you calling ageTest method, then you will get compiletime error.
MyCustomExceptionTest.java
public class MyCustomExceptionTest {
public static void main(String[] args){
try{
MyCustomExceptionTest.ageTest(15);
} catch(MyCustomException mce){
System.out.println(“Inside catch block: ” + mce.getMessage());
}
}
static void ageTest(int age) throws MyCustomException{
if(age < 18){
throw new MyCustomException(“Not eligible whose age is less than 18″);
}
}
}
class MyCustomException extends Exception {
private String message = null;
public MyCustomException() {
super();
}
public MyCustomException(String message) {
super(message);
this.message = message;
}
public MyCustomException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
OutPut:
Inside catch block: Not eligible whose age is less than 18
- Salesforce Certified Platform Developer I – Winter ’18 Release Exam - November 23, 2017
- Salesforce Certified Platform App Builder – Winter ’18 Release Exam - November 22, 2017
- Salesforce Certified Administrator – Winter’ 18 Release Exam - November 21, 2017