How to Create Java Custom Exception – Java Example Program

We can create our own exceptions by extending ‘Exception’ class. Below example will show you how to create custom exception by extending Exception class.

In the below example – the precondition is if age is less than 18 then it will throw exception and sets exception messages as “Not eligible whose age is less than 18″.

Here the custom exception class is – MyCustomException, that is extended from Exception and it has parameterized constructor that sets the exception message, and its call the superclass constructor by passing this message –

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.