Java 中 `throw` 和 `throws` 的区别详解

在 Java 中,throwthrows 都与异常处理相关,但它们的作用和使用场景完全不同。本文将详细解析 throwthrows 的区别,并通过示例代码加深理解。


1. throw

1.1 定义

throw 是一个关键字,用于在代码中手动抛出一个异常。

1.2 使用场景

  • 当程序检测到某种错误条件时,可以手动抛出异常。
  • 通常用于自定义异常或特定条件下的异常抛出。

1.3 语法

throw new ExceptionType("Error message");

1.4 示例

public class ThrowExample {
    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

    static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be at least 18");
        }
        System.out.println("Age is valid");
    }
}

输出:

Age must be at least 18

2. throws

2.1 定义

throws 是一个关键字,用于在方法签名中声明该方法可能抛出的异常类型。

2.2 使用场景

  • 当方法内部可能抛出检查异常(Checked Exception)时,需要在方法签名中使用 throws 声明。
  • 调用该方法的代码必须处理这些异常,或者继续向上抛出。

2.3 语法

returnType methodName(parameters) throws ExceptionType1, ExceptionType2 { ... }

2.4 示例

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ThrowsExample {
    public static void main(String[] args) {
        try {
            readFile("nonexistent.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }

    static void readFile(String fileName) throws FileNotFoundException {
        FileInputStream file = new FileInputStream(fileName);
        // 读取文件内容
    }
}

输出:

File not found: nonexistent.txt (系统找不到指定的文件。)

3. throwthrows 的区别

特性 throw throws
作用 手动抛出一个异常。 声明方法可能抛出的异常类型。
使用位置 方法内部。 方法签名中。
异常类型 可以抛出任何异常(检查异常或非检查异常)。 只能声明检查异常。
处理方式 抛出异常后,需要由调用者或 JVM 处理。 调用者必须处理或继续抛出。

4. 综合示例

以下是一个综合示例,展示 throwthrows 的结合使用:

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ThrowAndThrowsExample {
    public static void main(String[] args) {
        try {
            processFile("nonexistent.txt");
        } catch (FileNotFoundException e) {
            System.out.println("Caught exception: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    static void processFile(String fileName) throws FileNotFoundException {
        if (fileName == null || fileName.isEmpty()) {
            throw new IllegalArgumentException("File name cannot be null or empty");
        }
        FileInputStream file = new FileInputStream(fileName);
        // 处理文件内容
    }
}

输出:

Caught exception: nonexistent.txt (系统找不到指定的文件。)

5. 注意事项

  1. throwthrows 的结合使用

    • 在方法内部使用 throw 抛出异常时,如果异常是检查异常,必须在方法签名中使用 throws 声明。
    • 非检查异常(如 RuntimeException)不需要在方法签名中声明。
  2. 异常传播

    • 使用 throws 声明的异常会沿着调用栈向上传播,直到被捕获或导致程序终止。
  3. 自定义异常

    • 可以通过继承 ExceptionRuntimeException 创建自定义异常,并使用 throw 抛出。

6. 总结

  • throw:用于在代码中手动抛出异常。
  • throws:用于在方法签名中声明可能抛出的异常类型。

你可能感兴趣的:(java,java,开发语言)