(Translated by https://www.hiragana.jp/)
User-defined Custom Exception in Java - GeeksforGeeks
Open In App

User-defined Custom Exception in Java

Last Updated : 02 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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 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 the object value of the key from HashMap. On runtime, JVM processes hash code for each object and gives it on interest. When we
3 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
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
Array Index Out Of Bounds Exception in Java
Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This
4 min read
Types of Exception in Java with Examples
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in excep
8 min read
Different Ways to Print Exception Messages in Java
In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object. Methods to Print Exceptions in Java There are three methods to print exception messages in Java. These are: 1. java.
2 min read
Output of Java program | Set 12(Exception Handling)
Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exce
3 min read
Understanding OutOfMemoryError Exception in Java
In Java, all objects are stored in a heap. They are allocated using a new operator. The OutOfMemoryError Exception in Java looks like this: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space Usually, this error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory. No more memory could be
9 min read
Null Pointer Exception In Java
NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Reason for Null Pointer ExceptionThese are certain reasons for Null Pointer Exception as mentioned below: Invoking a method from
6 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Exception handling in JSP
Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages. There are two ways of handling exceptions in JSP. They are: By errorPage and isErrorPage attributes of page directiveBy <error-page>
3 min read
Exception Handling in Apache Kafka
Exception handling is an important aspect of any software system, and Apache Kafka is no exception. In this article, we will discuss the various types of exceptions that can occur in a Kafka system and how to handle them. First, it is important to understand the basic architecture of Kafka. A Kafka system consists of a number of brokers, which are
6 min read
How to Handle the SSL(HTTPs) Certification Path Exception in Android Applications?
If you haven't been stung by the below-mentioned exception when running a Java program created by you on your system that connects to an SSL server (HTTPS), be prepared for a bad experience at some time in your development career. Exception: PKIX path construction failed: sun.security.provider.certpath.SunCertPathBuilder Exception: No valid certifi
4 min read
Servlet - Exception Handling
When a servlet throws an exception, the web container looks for a match with the thrown exception type in web.xml configurations that employ the exception-type element. To define the invocation of servlets in response to particular errors or HTTP status codes, you'd have to utilize the error-page element in web.xml. Exception Handling is the proces
4 min read
Spring MVC - Exception Handling
Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generate
6 min read
JUnit 5 - Expected Exception
In JUnit 5, Exception handling is changed compared to exception handling in JUnit 4. JUnit 5 provides the assertThrows() method for that particular exception thrown during execution of the Testing of an application. This assertThrows is available in org.junit.jupiter.api.Assertions class. Mostly this assertThrows() is used for testing expected exce
3 min read
Exception Handling in C++
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. The process of handling these exceptions is called exception handling. Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code. So basica
10 min read
Exception Handling in Spring Boot
Exception handling in Spring Boot helps to deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Here are some key approaches to exception handling in Spring
8 min read
Python Exception Handling
We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4).  In this article, we will discuss how to handle exceptions in Python using try, except, and finally statements with the help of proper examples.  Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a program due to which
9 min read
How to Import Custom Class in Java?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
How to Create Custom Class in Java?
Class is the collection of objects. Class is not a real-world entity it is just only templates and prototypes or blueprints. Class does not occupy memory. We can write a custom class as per our choice for an illustration purpose a sample is shown in the program below as a helper class. Example: Java Code // Java Program to Creating our Own Custom C
2 min read
How to Build a Custom Collector in Java?
Java Collector is the utility class that provides many helpful methods and functions for the collector interface. Mainly collector implementation is used with the stream collect() method. The collector interface was provided by Java 8 under the part of the newly introduced Java Stream API. This interface provides various methods to perform mutual r
5 min read
Difference Between Daemon Threads and User Threads In Java
In Java, there are two types of threads: Daemon ThreadUser Thread Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks. Differ
4 min read
How to read a Matrix from user in Java?
Given task is to read a matrix from the user. The size and number of elements of matrices are to be read from the keyboard. // Java program to read a matrix from user import java.util.Scanner; public class MatrixFromUser { // Function to read matrix public static void readMatrixByUser() { int m, n, i, j; Scanner in = null; try { in = new Scanner(Sy
2 min read
Practice Tags :