18)Learn how to create and use custom exceptions.

PHOTO EMBED

Mon Jul 08 2024 06:14:48 GMT+0000 (Coordinated Universal Time)

Saved by @varuntej #java

// Custom exception class
class NegativeNumberException extends Exception {
    public NegativeNumberException(String message) {
        super(message);
    }
}

// Class using the custom exception
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int result = calculateSquare(5);
            System.out.println("Square: " + result);

            result = calculateSquare(-3); // This will throw NegativeNumberException
            System.out.println("Square: " + result); // This line won't be executed
        } catch (NegativeNumberException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Method that may throw the custom exception
    private static int calculateSquare(int number) throws NegativeNumberException {
        if (number < 0) {
            // Throw the custom exception if the number is negative
            throw new NegativeNumberException("Negative numbers are not allowed.");
        }
        return number * number;
    }
}
content_copyCOPY