The Wayback Machine - https://web.archive.org/web/20240708001232/https://www.geeksforgeeks.org/user-defined-custom-exception-in-java/
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
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
Using TreeMap to sort User-defined Objects in Java
Given example shows how to sort user defined objects TreeMap, you can sort the keys based on the logic provided inside the method. Given a record of employees name and salary as positive integer, it is required to sort the records on the basis of employee salary, using TreeMap in Java. If salary is same, then use employee name for comparison. Examp
2 min read
How to create a user defined javap tool?
What is a javap tool? The javap tool is used to get the information of any class or interface. The javap command (also known as the Java Disassembler) disassembles one or more class files. Its output depends on the options used ("-c" or "-verbose" for byte code and byte code along with innards info, respectively). If no options are used, javap prin
4 min read
Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
If we want to get the result of the function in Java, for example, the method mentioned below: convert(a,process(covertToInt(b),convertToInt(c)))The tool or solution we can refer to is mentioned below. So, In this article, we will learn about Parsing Nested User-Defined Functions using SpEL. What is Spring Expression Language (SpEL)? SpEL, or Sprin
3 min read
Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Exception Propagation in Java
Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something
3 min read
Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t
6 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
Infinity or Exception in Java when divide by 0?
Consider the following code snippets: public class Geeksforgeeks { public static void main(String[] args) { double p = 1; System.out.println(p/0); } } Output: Infinity public class Geeksforgeeks { public static void main(String[] args) { int p = 1; System.out.println(p/0); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by z
1 min read
Practice Tags :
three90RightbarBannerImg