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

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

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