杰瑞科技汇

Java中catch和throw如何协同处理异常?

Of course! Let's break down throw and catch in Java, which are the two fundamental parts of exception handling.

Java中catch和throw如何协同处理异常?-图1
(图片来源网络,侵删)

First, a simple analogy:

Imagine you're in a kitchen (your code). You ask a chef to chop vegetables (call a method). The chef has a sharp knife (a tool with potential danger). If the chef gets distracted, they might cut themselves (an error occurs).

  • throw: This is the chef shouting, "Ouch! I cut my finger!" They are throwing the problem (a "cut finger" object) at you, the head chef.
  • try-catch: This is you, the head chef, having a first-aid kit nearby (a try-catch block). You try to chop vegetables, but if the junior chef yells "Ouch!", you catch the "cut finger" object and apply a bandage (handle the error).

throw — Throwing an Exception

The throw keyword is used to explicitly create an instance of an Exception (or a subclass of it) and "throw" it. This immediately stops the normal flow of the program and looks for a catch block that can handle it.

Key Points for throw:

  1. You create an Exception object: new Exception("This is a message");
  2. You use the throw keyword: throw new Exception("This is a message");
  3. The method signature must declare it: If a method can throw a checked exception, it must declare this in its signature using the throws keyword. (Unchecked exceptions like RuntimeException don't need to be declared).

Example of throw:

Let's create a method that checks a person's age. In our system, the age cannot be negative.

Java中catch和throw如何协同处理异常?-图2
(图片来源网络,侵删)
public class AgeChecker {
    // This method can throw a checked exception, so we must declare it with 'throws'
    public void checkAge(int age) throws InvalidAgeException {
        System.out.println("Checking age: " + age);
        if (age < 0) {
            // We are explicitly creating and throwing our custom exception
            throw new InvalidAgeException("Age cannot be negative!");
        }
        System.out.println("Age is valid.");
    }
}
// A custom exception class (a good practice)
class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message); // Call the constructor of the parent Exception class
    }
}

In this example, if age is -5, the throw new InvalidAgeException(...) line is executed. The program jumps out of the checkAge method and looks for a catch block that can handle an InvalidAgeException.


try-catch — Catching an Exception

The try-catch block is used to handle exceptions that might be thrown by code within the try block. It allows your program to catch an exception, deal with it gracefully, and continue running instead of crashing.

The Structure:

try {
    // Code that might throw an exception
    // This is the "dangerous" code
} catch (SpecificExceptionType e) {
    // Code to run if a SpecificExceptionType is thrown
    // 'e' is a reference to the thrown exception object
} catch (AnotherExceptionType e) {
    // Code to run if another type of exception is thrown
} finally {
    // (Optional) This block ALWAYS runs, whether an exception occurred or not.
    // Often used for cleanup (e.g., closing files, database connections).
}

Example of try-catch:

Now, let's use the AgeChecker class from above and handle the potential exception.

public class Main {
    public static void main(String[] args) {
        AgeChecker checker = new AgeChecker();
        // Scenario 1: Valid age
        System.out.println("--- Scenario 1: Valid Age ---");
        try {
            checker.checkAge(25);
        } catch (InvalidAgeException e) {
            // This block will NOT run in this scenario
            System.out.println("Caught an exception: " + e.getMessage());
        }
        System.out.println("Finished Scenario 1.\n");
        // Scenario 2: Invalid age (will throw an exception)
        System.out.println("--- Scenario 2: Invalid Age ---");
        try {
            // This line will throw InvalidAgeException
            checker.checkAge(-5); 
        } catch (InvalidAgeException e) {
            // This block WILL run because the 'try' block threw our specific exception
            System.out.println("Caught an exception: " + e.getMessage());
        }
        System.out.println("Finished Scenario 2.\n");
        // Scenario 3: Using 'finally'
        System.out.println("--- Scenario 3: Using 'finally' ---");
        try {
            checker.checkAge(50);
        } catch (InvalidAgeException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        } finally {
            // This will run regardless of an exception
            System.out.println("This 'finally' block always executes.");
        }
        System.out.println("Finished Scenario 3.");
    }
}

Output of the code above:

Java中catch和throw如何协同处理异常?-图3
(图片来源网络,侵删)
--- Scenario 1: Valid Age ---
Checking age: 25
Age is valid.
Finished Scenario 1.
--- Scenario 2: Invalid Age ---
Checking age: -5
Caught an exception: Age cannot be negative!
Finished Scenario 2.
--- Scenario 3: Using 'finally' ---
Checking age: 50
Age is valid.
This 'finally' block always executes.
Finished Scenario 3.

The throws Keyword (Important Distinction)

It's crucial not to confuse throw and throws.

  • throw: A keyword used inside a method to manually create and throw an exception object.
  • throws: A keyword used in a method signature to declare that the method might throw a particular type of exception. It's a way of "passing the buck" to the caller, saying, "I might have a problem, so you need to handle it."

Example of throws:

In our AgeChecker example, the method signature was: public void checkAge(int age) throws InvalidAgeException

This means: "This method checkAge might throw an InvalidAgeException. The caller (the main method in this case) is responsible for handling it, either with a try-catch block or by declaring it in its own throws clause."

If we had not used try-catch in the main method, the code would not compile.

// This will NOT COMPILE!
public class Main {
    public static void main(String[] args) {
        AgeChecker checker = new AgeChecker();
        // Compiler error: unreported exception InvalidAgeException; must be caught or declared to be thrown
        checker.checkAge(-5); 
    }
}

Summary Table

Keyword Purpose Where it's used Example
throw To create and throw an exception object. Inside a method's body. throw new IOException("File not found");
catch To handle an exception that was thrown. In a try-catch block. catch (IOException e) { ... }
throws To declare that a method might throw an exception. In a method signature. public void readFile() throws IOException { ... }
try To enclose code that might throw an exception. The start of a try-catch block. try { ... }
分享:
扫描分享到社交APP
上一篇
下一篇