Because our own exceptions are derived classes of Exception, Java allows us to create them. A custom exception or user-defined exception is one we create on our own. Java custom exceptions are used to tailor the exception to user requirements. A User-Defined Exception, also known as a custom exception, is your own exception class that you create and then throw using the keyword “throw.”
Let’s see a simple example of a Java custom exception. In the following code, the constructor of InvalidAgeException takes a string as an argument. This string is passed to the constructor of the parent class Exception using the super() method. Also, the constructor of the Exception class can be called without using a parameter, and calling super() method is not mandatory.
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote"); }
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println(" Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}
Caught the exception
Exception occured: age is not valid to vote
rest of the code...
Note: also read about the Interface vs Abstract class
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…