Creating User Defined Exceptions in Java

Introduction

Customized exceptions are necessary to handle abnormal conditions of applications created by the user. The advantage of creating such an exception class is that, according to situations defined by the user, an exception can be thrown. It is also possible to set any condition or value to a variable and generate a user-defined exception. For example, it is possible to check if the input is greater than, equal to, or lesser than a predefined number and accordingly generate exceptions.

Example to create a user-defined exception.

Source Code

import java.io.*;

class MyException extends Exception {
    private int a;

    MyException(int b) {
        a = b;
    }

    public String toString() {
        return "MyException [" + a + "]";
    }
}

class UserdefException {
    public int x;
    final int k = 5;

    void getInt() {
        try {
            BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Do some guess work to generate your own exception");
            System.out.println("Enter a number between 1 and 10");
            System.out.println("Between these numbers lies the number to generate your own exception");

            String line;
            while ((line = dis.readLine()) != null) {
                x = Integer.parseInt(line);
                if (x == 5) {
                    System.out.println("Congrats!! You have generated an exception!!");
                    throw new MyException(x);
                } else {
                    System.out.println("Wrong Guess!! Try again");
                }
            }
        } catch (MyException m) {
            System.out.println("Generated Exception: " + m);
        } catch (NumberFormatException n) {
            System.out.println("Sorry !! No Characters");
            System.out.println("Exiting....");
            System.out.println("Generated Exception: " + n);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        UserdefException u = new UserdefException();
        u.getInt();
    }
}

Output

Command Prompt

And if the user enters the number, say 11, then the output shows here

Description of the code

This code demonstrates the creation and use of a custom exception class, along with handling user input to trigger the exception under specific conditions. The MyException class is a custom exception that extends the standard Exception class. It includes an integer field a and an overridden toString() method, which provides a custom message that incorporates the value of a. The main class, UserdefException, contains a method called getInt() that interacts with the user by prompting them to guess a number between 1 and 10. If the user correctly guesses the number 5, the program acknowledges the correct guess by throwing the custom MyException.

If the guess is incorrect, the user is prompted to try again. The code also includes exception handling for MyException to display a custom message, as well as handling for NumberFormatException to manage cases where the user inputs a non-integer, prompting an error message and exiting the program. An empty catch block for IOException is also present to handle any potential input/output errors. This code effectively illustrates how to use custom exceptions in Java, along with basic input and exception-handling techniques.

System Exceptions

  • ArrayIndexOutOfBoundsException: When the array index is invalid.
  • CharConversionException:  For character conversion problems during ObjectStreamWriter operations.
  • EOFException:  For signaling the reading of end-of-file.
  • FileNotFoundException: For signaling where a requested file is not found.
  • IOException: For general problems during I/O operations.
  • InterruptedIOException: For Signaling that an I/O operation was interrupted.
  • InvalidClassException: When unable to re-create a class during deserialization.
  • NegativeArraySizeException: When array size is negative.
  • NumberFormatException: When the string passed, it is not a number.
  • SQLException:  When an error occurs during a database access.
  • UnknownHostException: When the host cannot be located.

Summary

User-defined exceptions in Java are custom exceptions created by developers to handle specific abnormal conditions within an application. These customized exceptions offer the flexibility to define and manage exceptions according to the unique requirements of a particular situation. By creating a custom exception class, developers can throw exceptions based on specific conditions, such as whether an input value is greater than, equal to, or less than a predefined number. This approach allows for more precise error handling, making the application more robust and tailored to specific needs.


Similar Articles