In this tutorial, we will learn about Custom Exception in Java. Custom Exceptions are also known as a user-defined exception. The main motive of creating a custom exception is to create a new exception according to project requirement. When you create a custom exception you have to inherit Exception class as a parent in your custom exception class. please check out the following example.
Page Contents
Example Program:
//creating an custom Exception class
class MyCustomException extends Exception{
public MyCustomException(){
System.out.println("Constucor of MyCustomException invoked");
}
public String getMessage() {
return "Hello, This is getMessage() in MyCustomException";
}
}
public class Example{
public static void main(String args[]){
try{
System.out.println("In try block");
throw new MyCustomException(); //throwing exception explicitly
}catch(MyCustomException e){
System.out.println(e.getMessage());
System.out.println("In catch block");
}
}
}
Output:
In try block
Constucor of MyCustomException invoked
Hello, This is getMessage() in MyCustomException
In catch block
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
