×

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line that caused the Exception has never been executed.

In Java, users can make custom exceptions that are derived classes from the super Exception class. Custom exceptions or user-defined exceptions are those we create on our own. Java custom exceptions are generally utilized to customize the Exception to user needs.

The example sample 1 is a user-defined exception which contains invaliAge, which extends the Exception class.

You will provide us with your exception description by using the custom exception. The getMessage() function on the object we generated may be used to retrieve a message, which we have supplied to the function Object()  of the inheritance hierarchy, the Exception class, in this case.

Need to use the user-defined exceptions

Most of the common types of computing exceptions are covered by Java exceptions. But often, we have to make exceptions.

A few arguments for using the user-defined exceptions are as follows:

  • To detect a subset of current Java exceptions and give them specific conditions.
  • Exceptions to business logic These include business logic or process exceptions. Understanding the exact issue is helpful for both application users and programmers.

We must modify the Java Exception class to create customised exceptions in Java.lang package.

Example for creation of a user-defined exception in Java:

public class NameoftheFile extends Exception {  
    public NameoftheFile(String exception) {  
    super(exception);  
    }  
}  

Example 1:

Now let us look at a basic Java user-defined exception example. The function Object()  of the Exception in the sample code accepts a string as an input. The super() function is used to give this string to the function Object() of the superclass Exceptions. Similarly, there is no requirement to invoke the super() method or use an argument when calling the function Object() of the Exception class. 

UserDefinedException1.java

// class UserDefinedException1 denotes the creation of user-defined exception
class AgeException extends Exception  
{  
    public AgeException(String st)  
    {  
        // A constructor of the Parent class Exception is called  
        super(st);  
    }  
}  
    
// class using the user-defined AgeException  
public class UserDefinedException1  
{  
  
    //this block contains the method for checking the age condition 
    static void check(int age) throws  AgeException 
    {
       if(age < 18)
       {  
  
        //  an object is used for throwing the Exception
        throw new AgeException("Invalid age");    
       }  
       else
      {   
        System.out.println("Person can eligible");   
      }   
     }    
  
    // main section of the program 
    public static void main(String args[])  
    {  
        try  
        {  
            // calling the check method   
            check(15);  
        }  
        catch (AgeException e)  
        {  
            System.out.println("Found an exception");  
    
            //the message is printing from the AgeException class  
            System.out.println("The Exception occurred is: " + e);  
        }  
  
        System.out.println("Other lines of the code....");    
    }  
}  

Output:

User Defined Exception in Java

In the above example, when the personage(page) is passed as 15, then it displayed that there occurred an exception Invalid age.

Example 2:

UserDefinedException2.java

// class UserDefinedException2 denotes the user-defined exception 
class MyException extends Exception  
{  
    
}  
    
// MyException class using the user-defined Exception 
public class UserDefinedException2
{  
    // main section  
    public static void main(String args[])  
    {  
        try  
        {  
            // an object is used for throwing the Exception
            throw new MyException();  
        }  
        catch (MyException ex)  
        {  
            System.out.println("found an exception");  
            System.out.println(ex.getMessage());  
        }  
  
        System.out.println("other lines of code");    
    }  
}  

Output:

User Defined Exception in Java

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.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 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 Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.