Exception Class in Java

An error is a problem, bug, or human-created mistake that arises at the time of execution of a program. An exception interrupts the flow of the program and terminates it abnormally. The termination of the program abnormally is not recommended, and for that, we need to handle these exceptions.

Java provides Java.lang.Exception class for handling the exceptions which inherit the properties and methods of Object and Throwable class.

Methods of java.lang.Throwable class

addSuppressed(), fillInStackTrace(), getCause(), getLocalizedMessage(), getMessage(), getStackTrace(), getSuppressed(), initCause(), printStackTrace(), printStackTrace(), printStackTrace(), setStackTrace(), and toString().

Methods of java.lang.Object class

clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), and wait().

The Exception class has a set of sub-classes for handling different types of exceptions such as IOException, NotBoundException, and NotOwnerException etc.

All the subclasses of the Exception class are in the form of Throwable that indicates the conditions that an application wants to catch.

The Exception class provides the following 5 constructors:

1. public Exception()

The public Exception () construct an exception with a null detail message. The cause can be subsequently initialized by calling Throwable.initCause(Java.lang.Throwable). It is a default constructor and takes no parameters for message and Throwable cause.

2. public Exception(String message)

The public Exception( String message) construct a new exception with the given detailed message. Just like the default constructor, the cause can be subsequently initialized by calling Throwable.initCause(Java.lang.Throwable). It is a parameterized constructor which takes a parameter of type String for detail message. The detail message is saved so that the Throwable.getMessage() method can retrieve it.

Parameters

  1. message
    It is of type string for the error message or detail message.
  2. 3. public Exception(String message, Throwable cause)

    It is another variation of the Exception () constructor, which takes two parameters, i.e., message and cause. It constructs a new exception with the given detailed message and cause. The message associated with the cause will not be automatically included in the exception detail message.

    Parameters

    1. message
      It is of type string for the error message or detail message.
    2. cause
      The cause is saved so that the Throwable.getCause() method can retrieve it. The null value defines that the cause is nonexistent or unknown.

    4. public Exception(Throwable cause)

    It is another variation of the Exception () constructor, which takes only a single parameter, i.e., cause. The constructor creates an Exception with the given cause and the detailed message of the cause.

    It is mainly used for the exceptions, which are more than wrappers for other throwables.

    Parameters

    1. cause

    The cause is saved so that the Throwable.getCause() method can retrieve it. The null value defines that the cause is nonexistent or unknown.

    5. protected Exception(String message, Throwable cause, Boolean enableSuppression, Boolean writableStackTrace)

    It is a little different from the other constructors. It is also a parameterized constructor and takes 4 parameters, i.e., message, cause, enableSuppression, and writableStackTrace.

    It creates an exception with the specified parameters.

    Parameters

    1. message
      It is a detailed message.
    2. cause
      The cause is saved so that the Throwable.getCause() method can retrieve it. The null value defines that the cause is nonexistent or unknown.
    3. enableSuppression
      It is a Boolean value that defines whether the suppression is enabled or not.
    4. writableStackTrace
      It is a Boolean value that defines whether the stack trace is writable or not.

    Create custom exceptions using the Exception class

    We have a series of predefined exceptions in Java. Many times, we need to create our own Exception for handling errors. We used the custom exception for customizing the exceptions as per the user need.

    Let's take some examples of the Exception class and understand how we can create our own Exception in Java.

    CustomExceptionExample1.java

    Output:

    Exception Class in Java

    Description:

    In the above code, we create a custom exception, InvalidAgeException. We take input from the user for checking whether the user is eligible for the exam or not. We call the checkEligibility() method by passing the user input to it. The checkEligibility() method checks whether the given age is greater than 18 or not because a user having age 18+ is eligible for the exam. The method throws InvalidAgeException when it finds an age less than 18. The catch block in the main() method will handle this Exception and print the detailed message of the Exception.

    CustomExceptionExample2.java

    Output:

    Exception Class in Java

    Description:

    In the above code, we create the custom exception AlreadyExistException. We take input from the user to add it in the languages ArrayList. We call the checkExistence() method by passing the user input and the languages ArrayList to it. The checkExistence() method checks whether the given language is available in the languages ArrayList or not. The method throws AlreadyExistException when it finds the user input language in the languages ArrayList. The catch block in the main() method will handle this Exception and print the detailed message of the Exception. If the checkExistence() method doesn't find the given language in the languages ArrayList, it will add the user input language in the languages ArrayList.






Latest Courses