Creating and Throwing Custom Exceptions in Java

Beantwortet mit GPT-4o-mini von Java Q&A Hub

Frage:

Write a Java program to create and throw custom exceptions.

Antwort:

Certainly! Below is a simple Java program that demonstrates how to create and throw custom exceptions. In this example, we will create a custom exception called InvalidAgeException that will be thrown when an invalid age is provided (e.g., a negative age or an age greater than 150).

Custom Exception Class

First, we will create the custom exception class:

// InvalidAgeException.java
public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

Main Class

Next, we will create a main class that uses this custom exception:

// Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        try {
            validateAge(age);
            System.out.println("Your age is: " + age);
        } catch (InvalidAgeException e) {
            System.out.println("Exception: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 0 || age > 150) {
            throw new InvalidAgeException("Age must be between 0 and 150.");
        }
    }
}

Explanation

  1. Custom Exception Class:

    • InvalidAgeException extends the Exception class. It has a constructor that takes a message string, which is passed to the superclass constructor.
  2. Main Class:

    • We use a Scanner to read user input for age.
    • The validateAge method checks if the age is valid. If the age is less than 0 or greater than 150, it throws an InvalidAgeException.
    • In the main method, we call validateAge inside a try-catch block to handle the custom exception. If an exception is thrown, we catch it and print the error message.

Running the Program

To run this program, you can create two files: InvalidAgeException.java and Main.java. Compile both files and run the Main class. The program will prompt you to enter your age and will validate it, throwing an exception if the age is invalid.

Example Output

  1. Valid Age:

    Enter your age: 25
    Your age is: 25
    
  2. Invalid Age:

    Enter your age: -5
    Exception: Age must be between 0 and 150.
    

This example illustrates how to create and throw custom exceptions in Java effectively.