杰瑞科技汇

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

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

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

The Big Picture: Why Exception Handling?

Imagine you're driving a car. You don't expect a tire to blow out every time, but you know it could happen. You prepare for it by having a spare tire in the trunk.

In programming, exceptions are like unexpected events (a flat tire). Your program can crash if it's not prepared for them. Exception handling (try, catch, throw, throws) is your program's "spare tire." It allows your code to:

  1. Anticipate potential problems (try).
  2. React to them gracefully when they happen (catch).
  3. Signal that a problem has occurred (throw).

The throw Keyword

The throw keyword is used to explicitly create and throw an exception. You use it when your code detects an error condition that it cannot handle itself.

Key Points about throw:

  • It's used inside a method.
  • You create an object of a class that extends Throwable (usually Exception or one of its subclasses).
  • When you throw an exception, the normal flow of the program is immediately stopped. The JVM looks for a catch block that can handle this type of exception.

Syntax:

throw new ExceptionType("Error message");

Example:

Let's create a method that checks if a user is old enough to vote. If not, we'll throw an exception.

Java中throw与catch如何协同处理异常?-图2
(图片来源网络,侵删)
public class VoterChecker {
    public static void checkVotingAge(int age) {
        // Check if the age is less than 18
        if (age < 18) {
            // Create a new IllegalArgument exception and throw it
            throw new IllegalArgumentException("You must be at least 18 years old to vote.");
        }
        // This line will only execute if the age is 18 or older
        System.out.println("You are eligible to vote.");
    }
    public static void main(String[] args) {
        System.out.println("Checking for a 20-year-old...");
        checkVotingAge(20); // This will work fine
        System.out.println("\nChecking for a 16-year-old...");
        try {
            checkVotingAge(16); // This will throw an exception
        } catch (IllegalArgumentException e) {
            // We'll see how to catch this in the next section
            System.out.println("Caught an exception: " + e.getMessage());
        }
        // The following line will NOT be executed because the exception was thrown
        // and caught. If it wasn't caught, the program would crash here.
        System.out.println("This line is after the call to checkVotingAge(16).");
    }
}

Output:

Checking for a 20-year-old...
You are eligible to vote.
Checking for a 16-year-old...
Caught an exception: You must be at least 18 years old to vote.
This line is after the call to checkVotingAge(16).

The catch Keyword

The catch keyword is used to handle an exception that has been thrown. You place it after a try block. The try block contains the code that might throw an exception.

The try-catch Block

You almost always use catch with a try block.

Syntax:

try {
    // Code that might throw an exception
    riskyMethod();
} catch (ExceptionType1 e1) {
    // This block runs only if an ExceptionType1 is thrown
    System.out.println("Caught an ExceptionType1: " + e1.getMessage());
} catch (ExceptionType2 e2) {
    // This block runs only if an ExceptionType2 is thrown
    System.out.println("Caught an ExceptionType2: " + e2.getMessage());
}

How it Works:

  1. The code inside the try block is executed.
  2. If an exception occurs, the rest of the try block is skipped.
  3. The JVM looks for a catch block whose parameter (e1, e2) matches the type of the exception that was thrown.
  4. If a matching catch block is found, its code is executed.
  5. If no matching catch block is found, the program terminates abruptly.

Example:

Let's extend our previous example. The main method now calls checkVotingAge(16) inside a try block.

Java中throw与catch如何协同处理异常?-图3
(图片来源网络,侵删)
public class VoterChecker {
    public static void checkVotingAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age cannot be less than 18.");
        }
        System.out.println("Voting eligibility confirmed.");
    }
    public static void main(String[] args) {
        System.out.println("Attempting to process a 16-year-old's registration...");
        try {
            // This line is "risky" because it might throw an exception
            checkVotingAge(16); 
            System.out.println("This line will not be printed.");
        } catch (IllegalArgumentException e) {
            // This block catches the specific exception we threw
            System.out.println("Error: " + e.getMessage());
        }
        System.out.println("\nProgram continues running smoothly after handling the error.");
    }
}

Output:

Attempting to process a 16-year-old's registration...
Error: Age cannot be less than 18.
Program continues running smoothly after handling the error.

Notice how the program didn't crash. It gracefully handled the error and continued executing.


Putting It All Together: try, catch, and throw

This is the most common pattern in Java. You write code that might encounter a problem (try). If a problem is found, you signal it by throwing an exception. You then handle that exception in a catch block.

A More Complete Example: Bank Account

Let's model a simple bank account where you can't withdraw more money than you have.

// A custom exception to make our code more readable
class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}
class BankAccount {
    private double balance;
    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }
    // This method might throw an exception
    public void withdraw(double amount) throws InsufficientFundsException {
        // Check for a potential error condition
        if (amount > balance) {
            // If the condition is met, create and throw a custom exception
            throw new InsufficientFundsException("Withdrawal failed. Not enough funds. Balance: " + balance);
        }
        // If the withdrawal is successful, proceed
        balance -= amount;
        System.out.println("Withdrawal successful. New balance: " + balance);
    }
}
public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(1000.00);
        System.out.println("Attempting to withdraw $500...");
        try {
            account.withdraw(500); // This will work
        } catch (InsufficientFundsException e) {
            System.out.println("Caught an error: " + e.getMessage());
        }
        System.out.println("\nAttempting to withdraw $800...");
        try {
            // This will fail and throw our custom exception
            account.withdraw(800); 
        } catch (InsufficientFundsException e) {
            // This catch block will handle it
            System.out.println("Caught an error: " + e.getMessage());
        }
        System.out.println("\nProgram finished.");
    }
}

Output:

Attempting to withdraw $500...
Withdrawal successful. New balance: 500.0
Attempting to withdraw $800...
Caught an error: Withdrawal failed. Not enough funds. Balance: 500.0
Program finished.

throws Keyword (Bonus)

You might have noticed throws InsufficientFundsException in the method signature of withdraw. This is different from throw.

  • throw: Used to create and throw an exception object.
  • throws: Used in a method signature to declare that the method might throw a particular exception. It's a way of warning other programmers: "Hey, this method is risky. You need to handle the exception it might throw (either with a try-catch block or by declaring it in your own method signature)."

Summary Table

Keyword Purpose When to Use Example
throw Creates and throws an exception. When you detect an error condition in your code and want to signal it. if (age < 0) throw new IllegalArgumentException();
catch Handles an exception. After a try block, to define what to do if a specific type of exception occurs. catch (IOException e) { ... }
try Encloses code that might throw an exception. To group "risky" code that you want to monitor for exceptions. try { riskyCode(); }
throws Declares that a method can throw an exception. In a method signature to notify callers that they must handle the exception. public void readFile() throws IOException { ... }
分享:
扫描分享到社交APP
上一篇
下一篇