How to create custom checked Exception

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.

custom-checked-exception

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

Gopal Das
Follow me

Leave a Reply

Your email address will not be published. Required fields are marked *