×

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

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.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.