杰瑞科技汇

throw、throws在Java中的区别与用法?

Of course! This is a fundamental concept in Java for handling errors and exceptional conditions. Let's break down throw and throws clearly, as they are often confused.

throw、throws在Java中的区别与用法?-图1
(图片来源网络,侵删)

The Big Picture: Exception Handling in Java

In Java, errors can occur during program execution. These are called exceptions. For example:

  • Trying to access an array element at an invalid index (ArrayIndexOutOfBoundsException).
  • Dividing a number by zero (ArithmeticException).
  • Trying to access a file that doesn't exist (FileNotFoundException).

Java provides a robust mechanism to handle these exceptions gracefully, preventing your program from crashing. This is where throw and throws come in.


The throw Keyword

The throw keyword is used to explicitly create and throw an exception from a method or a block of code. It's like you are manually creating an error condition.

Key Characteristics of throw:

  • It's an executable statement. You use it inside a method or a block.
  • It is followed by an object of an exception class (e.g., new IOException()).
  • When throw is executed, it immediately stops the normal flow of the program and searches for a handler (a try-catch block) for that exception. If no handler is found, the program terminates.
  • You can only throw objects that are subclasses of Throwable (which includes Exception and Error).

Syntax:

throw new ExceptionClassName("Optional error message");

Example: throw in action

Imagine a method that validates a user's age. If the age is negative, it's an invalid input, so we should throw an exception.

throw、throws在Java中的区别与用法?-图2
(图片来源网络,侵删)
public class AgeValidator {
    // This method takes an age and validates it.
    public static void validateAge(int age) {
        // Check if the age is negative
        if (age < 0) {
            // If it is, explicitly create and throw an IllegalArgumentException
            throw new IllegalArgumentException("Age cannot be negative!");
        }
        System.out.println("Age is valid: " + age);
    }
    public static void main(String[] args) {
        System.out.println("Trying to validate age -5...");
        try {
            validateAge(-5); // This line will cause the exception to be thrown
        } catch (IllegalArgumentException e) {
            // Catch the specific exception that was thrown
            System.err.println("Error caught in main: " + e.getMessage());
        }
        System.out.println("\nTrying to validate age 25...");
        validateAge(25); // This will work fine
        System.out.println("Validation successful for age 25.");
    }
}

Output:

Trying to validate age -5...
Error caught in main: Age cannot be negative!
Trying to validate age 25...
Age is valid: 25
Validation successful for age 25.

In this example, validateAge throws an IllegalArgumentException when it encounters an invalid state. The main method catches it to handle the error gracefully.


The throws Keyword

The throws keyword is used in a method signature to declare that the method might throw a particular type of exception. It's a warning to the programmer calling this method: "Hey, be aware, this method can fail with an XException, so you need to handle it."

Key Characteristics of throws:

  • It is part of a method signature.
  • It lists the exceptions that the method can throw. It does not create the exception; it just declares the possibility.
  • It is used for checked exceptions (exceptions that are checked at compile-time, e.g., IOException, SQLException). Unchecked exceptions (like NullPointerException, ArithmeticException) do not need to be declared with throws.
  • If a method calls another method that declares a checked exception, the calling method must either:
    1. Handle it using a try-catch block, or
    2. Declare it in its own throws clause.

Syntax:

public void methodName() throws ExceptionClassName1, ExceptionClassName2 {
    // Method body that might call another method that throws these exceptions
}

Example: throws in action

Let's use Java's built-in FileReader class. Its constructor can throw a FileNotFoundException, which is a checked exception.

throw、throws在Java中的区别与用法?-图3
(图片来源网络,侵删)
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
    // This method declares that it might throw an IOException (the parent of FileNotFoundException)
    public void readFile(String fileName) throws IOException {
        System.out.println("Attempting to read file: " + fileName);
        // The FileReader constructor can throw a FileNotFoundException, which is a type of IOException.
        // Because it's a checked exception, we either handle it here or declare it in our method signature.
        // We are declaring it with 'throws'.
        FileReader reader = new FileReader(fileName);
        // In a real program, you would use the reader here...
        System.out.println("File opened successfully.");
        reader.close(); // This can also throw an IOException
    }
    public static void main(String[] args) {
        FileReaderExample example = new FileReaderExample();
        System.out.println("--- Calling readFile from a try-catch block ---");
        try {
            example.readFile("my_file.txt"); // Handle the potential exception
        } catch (IOException e) {
            System.err.println("Error: Could not read the file. " + e.getMessage());
        }
        System.out.println("\n--- Calling readFile without try-catch ---");
        // This will cause a COMPILE ERROR because readFile() declares it throws IOException,
        // and main() does not handle or declare it.
        // example.readFile("another_file.txt"); 
    }
}

Output (if my_file.txt doesn't exist):

--- Calling readFile from a try-catch block ---
Attempting to read file: my_file.txt
Error: Could not read the file. my_file.txt (No such file or directory)
--- Calling readFile without try-catch ---

If you uncomment the last line in main, the compiler will stop you with an error:

error: unreported exception IOException; must be caught or declared to be thrown
        example.readFile("another_file.txt");
        ^

Summary Table: throw vs. throws

Feature throw throws
Purpose To explicitly create and throw an exception object. To declare that a method can throw an exception.
Location Inside a method or a block of code. In the method signature.
Syntax throw new Exception(); public void method() throws Exception;
What it is An executable statement. A clause in the method declaration.
Exception Type Can throw any Throwable subclass (checked or unchecked). Used almost exclusively for checked exceptions.
Usage You use throw when your code detects an error condition that it cannot handle. You use throws to warn the caller that your method might not handle an exception and they need to be prepared.

Analogy: The Doctor's Office

  • throw: A doctor examining a patient discovers a serious problem (e.g., a broken bone). The doctor doesn't just ignore it; they throw a red flag and call for an ambulance.
  • throws: The hospital has a policy that any emergency room doctor throws a "potential fracture" report on their chart. This is a declaration to the head nurse and other doctors that this patient might need an orthopedic specialist. It's a warning to the rest of the system.

Putting It All Together

A method can use both throws and throw:

public void processUserInput(String input) throws IllegalArgumentException {
    if (input == null || input.trim().isEmpty()) {
        // The method detects a problem and throws an exception.
        throw new IllegalArgumentException("Input cannot be null or empty.");
    }
    // ... rest of the processing logic
}

Here, processUserInput declares (throws) that it might cause an IllegalArgumentException. Inside, it creates and throws (throw) that very exception when it finds invalid input. The caller is then responsible for catching this IllegalArgumentException.

分享:
扫描分享到社交APP
上一篇
下一篇