×

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

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Difference between Static and Instance Methods in Java

Static Method in Java The static technique has a place with the class as opposed to the object of the course. These are intended to be divided between every one of...

10 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.