×

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples.

Introduction

In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are now set off on pre-characterized conditions; for example, dividing a number by zero triggers to ArithmeticException. In the previous session, we found the built-in exceptions and resolved them using the try-catch block and throws on the output screens.

We can make our exception class in Java and try that Exception utilising the try-catch block. These exceptional cases are known as client characterised or custom exemptions.

To comprehend this instruction, we ought to have the essential information on try-catch, throw keywords and the basics of Exceptions.

An Exception is an event or issue during the program's execution. It will disturb the program's entire code and can't execute entirely, and get terminated instantly.

In Java programming language, we have a specific facility to create our exception-derived classes of Exception classes. Creating our Exception is known as a custom exception or user-defined Exception. Generally, User-defined exceptions are used to customise the Exception based on the user requirements. From the above statements, We can say that a Custom exception is creating our Exception and throwing the appeared Exception on the console or output screen by using the 'throw' keyword.

Custom exceptions in Java programming language are the exceptions that a developer creates to encounter the application's particular requirements. That's why it is also known as a user-defined Exception in Java.

For example:

1. Banking Application: Every customer who is willing to open their accounts must have at least 18 years old. But if the customer's age is less than 18 years, then the program for the specific requirements throws a custom exception by indicating the suggestions.

2. Voting age: If a citizen’s age is lesser than 18 years in India, then the program for this specific requirement throws "Invalid age" as a custom exception

Let's take an example of a user-defined Exception that is DemoException by extending the Exception class.

In the below example, we have created our Exception, which extends from Exception Class.

Purpose of Custom Exceptions

In Java programming java, there are a lot of exceptions occurred during the execution of the program. Sometimes, we must create exceptions, which we call custom exceptions.

There are specific reasons behind the use of custom exceptions. The following are a few reasons ….

  • To catch and give a particular treatment to a few sets of existing exceptions.
  • Business logic exceptions: There are many exceptions involved in Java related to own requirements and field. Business logic exceptions are related to business logic and workflow. It is beneficial for the users or the developers to understand the exact problem of the domain.

To create our won exceptions, we need to extend the Exception class that belongs to the lang package in Java.

Example:

In this example,we will pass a string to the constructor, a superclass of exception obtained using the "getMessage()” function on the object created.

Program:

 // Demoexception Class that represents user-defined Exception
 
class DemoException extends Exception {
    public DemoException(String s)
    {
        // it will call the constructor of the parent exception class
        super(s);
    }
}
 
// A Class that uses the above DemoException
public class Tutorialandexample {
    public static void main(String args[])
    {
        try {
            // Throw an object of user-defined Exception
            throw new DemoException(“Tutorialandexample");
        }
        catch (DemoException ex) {
            System.out.println("Caught an Exception");
 
            // Displaying the message from DemoException object System.out.println(ex.getMessage());
        }
    }
}

Output

Caught an Exception
Tutorialandexample

From the above code, we can clear that the constructor of DemoException requires a string as its argument. The argument is passed to the base class exception’s constructor using the super() keyword. The super key is not required if we don't want to give a parameter.

Program:

// Demo Class to represents user-defined exception
 
class DemoException extends Exception {
}
 
// A Jtp Class that uses the above DemoException
public class Jtp{
    public static void main(String args[])
    {
        try {
            // It will throw an object of custom Exception
            throw new DemoException();
        }
        catch (DemoException ex) {
            System.out.println("Caught an Exception");
            System.out.println(ex.getMessage());
        }
    }
}

Output

Caught an Exception
null


Related Topics

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.