Understanding `throw` vs `throws` in Java Exception Handling

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

difference between throw and throws keyword in java, with examples

回答:

In Java, both throw and throws are used in the context of exception handling, but they serve different purposes. Here’s a detailed explanation of each, along with examples.

throw Keyword

The throw keyword is used to explicitly throw an exception from a method or a block of code. When you use throw, you create an instance of an exception class and throw it, which can be caught by a try-catch block.

Example of throw:

public class ThrowExample {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or older.");
        } else {
            System.out.println("You are eligible to vote.");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        } catch (IllegalArgumentException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

Output:

Exception caught: Age must be 18 or older.

In this example, the checkAge method throws an IllegalArgumentException if the age is less than 18.

throws Keyword

The throws keyword is used in a method declaration to indicate that a method can throw one or more exceptions. It is a way of notifying the caller of the method that they need to handle these exceptions, either with a try-catch block or by declaring them in their own method signature.

Example of throws:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ThrowsExample {
    public static void readFile(String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        Scanner scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
        scanner.close();
    }

    public static void main(String[] args) {
        try {
            readFile("nonexistentfile.txt");
        } catch (FileNotFoundException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

Output:

Exception caught: nonexistentfile.txt (No such file or directory)

In this example, the readFile method declares that it can throw a FileNotFoundException. The caller of this method (in main) must handle this exception.

Summary

  • throw: Used to explicitly throw an exception. It is followed by an instance of an exception class.
  • throws: Used in a method signature to declare that the method can throw one or more exceptions. It informs the caller that they need to handle these exceptions.

Understanding the difference between throw and throws is crucial for effective exception handling in Java.