Open In App

User-defined Custom Exception in Java

Last Updated : 02 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own Exception is known as a custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the ‘throw’ keyword.

For example, MyException in the below code extends the Exception class. 

Why use custom exceptions?

Java exceptions cover almost all the general types of exceptions that may occur in the programming. However, we sometimes need to create custom exceptions.

Following are a few of the reasons to use custom exceptions:

  • To catch and provide specific treatment to a subset of existing Java exceptions.
  • Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem.

In order to create a custom exception, we need to extend the Exception class that belongs to java.lang package.

Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.

Java




// A Class that represents use-defined exception
 
class MyException extends Exception {
    public MyException(String s)
    {
        // Call constructor of parent Exception
        super(s);
    }
}
 
// A Class that uses above MyException
public class Main {
    // Driver Program
    public static void main(String args[])
    {
        try {
            // Throw an object of user defined exception
            throw new MyException("GeeksGeeks");
        }
        catch (MyException ex) {
            System.out.println("Caught");
 
            // Print the message from MyException object
            System.out.println(ex.getMessage());
        }
    }
}


 
 

Output

Caught
GeeksGeeks

 

In the above code, the constructor of MyException requires a string as its argument. The string is passed to the parent class Exception’s constructor using super(). The constructor of the Exception class can also be called without a parameter and the call to super is not mandatory. 

 

Java




// A Class that represents use-defined exception
 
class MyException extends Exception {
}
 
// A Class that uses above MyException
public class setText {
    // Driver Program
    public static void main(String args[])
    {
        try {
            // Throw an object of user defined exception
            throw new MyException();
        }
        catch (MyException ex) {
            System.out.println("Caught");
            System.out.println(ex.getMessage());
        }
    }
}


 
 

Output

Caught
null

 

 

 



Previous Article
Next Article

Similar Reads

How to create a Java HashMap of user defined class type?
Pre-requisite: Internal working of HashMap, HashMap If we wish to create a HashMap of our own class, we need to ensure that the hashcode() of the key of HashMap doesn't change as if it happens then it is impossible to get object value of the key from HashMap. On runtime, JVM processes hash code for each object and give it on interest. When we alter
3 min read
How to Avoid Duplicate User Defined Objects in TreeSet in Java?
TreeSet class in Java is part of Java’s collections framework which implements the NavigableSet interface, which provides functionalities to navigate through the SortedSet. The NavigableSet further extends the SortedSet interface, which provides functionalities to keep the elements sorted. As the TreeSet class implements a NavigableSet interface, i
5 min read
How to Sort a TreeSet with User Defined Objects in Java?
Comparator interface sorts the objects of user-defined classes. An object of the Comparator class is capable of comparing two objects of two different classes. Following function compare obj1 with obj2 TreeSet implements the SortedSet interface. So, duplicate values are not allowed.Objects in a TreeSet are stored in a sorted and ascending order.Tre
3 min read
How to Eliminate Duplicate User Defined Objects as a Key from Java LinkedHashMap?
Duplicate user-defined objects as a key from Java LinkedHashMap can be removed and achieved by implementing equals and hashcode methods at the user-defined objects. Example: Input : LinkedHashMap = [{[Apple, 40], Kashmir}, {[Grapes, 80], Nashik}] Duplicate key = {[Grapes, 80], Delhi} Output: LinkedHashMap = [{[Apple, 40], Kashmir}, {[Grapes, 80], D
2 min read
Java Program to Search User Defined Object From a List By Using Binary Search Using Comparator
The Comparator interface in Java can be used to compare user-defined objects. The Comparator interface is present in java.util package. Binary search is a searching algorithm that uses the divide and conquers rule to search the presence of an element in a list or array. The binary search algorithm works only on a sorted list. In case the list is no
6 min read
Java Program to Sort Keys in TreeMap by using Comparator with User Defined Objects
The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. To sort keys in TreeMap by using a comparator with user-defined objects in Java we have t
3 min read
How to Find User Defined Objects From LinkedHashSet in Java?
LinkedHashSet is used to store elements in which order they were inserted. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using
3 min read
User Defined Exceptions using Constructors in Java
In Java, we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException. In Java, we can create our own exception class and throw that exception using throw keyword. These
3 min read
Creating a User-Defined Printable Pair Class in Java
The pair class in C++ Standard Library is used a lot. We can implement our own user-defined pair class in Java and its object can be used anywhere just like any other parameter. Note : This class is equivalent to pair<int,int> class in java. You can create your own template or classes for other data types. Syntax For defining the pair class c
3 min read
User-Defined Packages in Java
Packages in Java are a mechanism to encapsulate a group of classes, interfaces, and sub-packages. In Java, it is used for making search/locating and usage of classes, interfaces, enumerations, and annotations easier. It can be considered data encapsulation also. In other words, we can say a package is a container of a group of related classes where
3 min read
Practice Tags :