Sobes.tech
Junior

How to write a custom (user-defined) exception in Java?

sobes.tech AI

Answer from AI

To create a custom exception in Java, follow these steps:

  1. Create a new class: Inherit it from an existing exception class. Most often, inherit from Exception or RuntimeException.
  2. Define constructors: Usually, define constructors that accept an error message (String) and/or a cause (Throwable).
  3. Add additional fields or methods (optional): If you need to store extra information about the exception.

Example of creating a simple custom exception:

// Custom exception for when a number is negative
public class NegativeNumberException extends Exception {

    // No-argument constructor
    public NegativeNumberException() {
        super();
    }

    // Constructor with error message
    public NegativeNumberException(String message) {
        super(message);
    }

    // Constructor with error message and cause
    public NegativeNumberException(String message, Throwable cause) {
        super(message, cause);
    }

    // Constructor with cause
    public NegativeNumberException(Throwable cause) {
        super(cause);
    }
}

Choosing between inheriting from Exception and RuntimeException depends on whether the exception is "checked" or "unchecked".

  • Inheriting from Exception: Creates a checked exception. It must be either caught (catch) or declared in the method signature (throws). Used for situations that can occur during normal program operation but require explicit handling (e.g., file not found).
  • Inheriting from RuntimeException: Creates an unchecked exception. It does not require mandatory handling or declaration. Used for errors that typically indicate problems in program logic or runtime environment (e.g., division by zero).

Using a custom exception:

public class ExampleUsage {

    // Method that can throw a custom exception
    public void processNumber(int number) throws NegativeNumberException {
        if (number < 0) {
            // Throw an instance of the custom exception
            throw new NegativeNumberException("Number cannot be negative: " + number);
        }
        // Logic to process the number
        System.out.println("Number processed: " + number);
    }

    public static void main(String[] args) {
        ExampleUsage example = new ExampleUsage();
        try {
            // Call a method that can throw an exception
            example.processNumber(10);
            example.processNumber(-5); // Exception will be thrown here
        } catch (NegativeNumberException e) {
            // Handle the custom exception
            System.err.println("Error: " + e.getMessage());
            //e.printStackTrace(); // You can print the stack trace for debugging
        }
    }
}
How to write a custom (user-defined) exception in… - sobes.tech