How to create a Custom Exception?
We need to extend the exception class in java.lang package to create our custom exception. With the following example, we will get a better understanding of it.
Example
// A class having the custom exception
class My_Exception extends Exception {
public My_Exception(String s)
{
// Calling constructor of parent Exception
super(s);
}
}
public class Main {
public static void main(String args[])
{
try {
// Throws an object of custom exception
throw new My_Exception("Coding Ninjas Studio");
}
// catches the exception
catch (My_Exception ex) {
System.out.println("Caught");
// Display the message from My_Exception object
System.out.println(ex.getMessage());
}
}
}
Output
Caught
Coding Ninjas Studio
Practice by yourself on java online compiler.
Explanation
In the example above, My_Exception requires a string as its argument so to the constructor of the parent class Exception, the string is passed using the getMessage() object. The call to super is not compulsory as the constructor of the parent class can also be called without a parameter.
Also read, Duck Number in Java and Hashcode Method in Java
FAQs
-
What is a custom exception?
When we create our own exception, it is known as a user-defined exception or custom exception, which is possible as Java allows it since they are basically derived classes of Exception.
-
What are the uses of a custom exception?
Most of the usual exceptions are covered in Java during programming. Still, we might need to create custom exceptions for specific purposes as it allows you to add methods and attributes that are not part of the standard exception and to catch and provide specific treatment to a subset of existing Java exceptions.
-
How to create a custom exception?
We need to extend the exception class in java.lang package to create our custom exception.
Conclusion
In this article, we have extensively discussed the following things:
- What is a custom exception?
- How is a custom exception created?
- Uses of custom exception.
We hope that this blog has helped you enhance your knowledge regarding User-defined Custom exceptions and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!