在Java中,throw
和 throws
是两个与异常处理相关的关键字,它们的功能和使用场景有所不同。下面详细介绍它们的区别以及适用情况,并附上相应的代码示例。
区别
1. throw
关键字
- 作用:
throw
关键字用于在方法体内部手动抛出一个异常对象。当程序在运行过程中遇到特定的错误或不符合预期的情况时,可以使用throw
来显式地触发异常。 - 语法:
throw new ExceptionType("异常信息");
- 位置:
throw
语句必须放在方法体内部。
2. throws
关键字
- 作用:
throws
关键字用于在方法声明中指定该方法可能会抛出的异常类型。它表示该方法本身不处理这些异常,而是将异常抛给调用者来处理。 - 语法:
returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... { ... }
- 位置:
throws
关键字必须放在方法声明的参数列表后面。
使用场景
1. throw
的使用场景
- 当程序中出现特定的错误条件,需要立即终止当前操作并抛出异常时,使用
throw
。例如,在自定义异常处理逻辑、验证输入参数等场景中。
2. throws
的使用场景
- 当方法内部可能会抛出某些异常,但该方法本身无法或不适合处理这些异常时,使用
throws
将异常抛给调用者。例如,在调用其他可能抛出异常的方法时,不想在当前方法中处理这些异常。
代码示例
// 自定义异常类
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ThrowAndThrowsExample {
// 使用 throw 关键字手动抛出异常
public static int divide(int dividend, int divisor) {
if (divisor == 0) {
// 当除数为 0 时,手动抛出异常
throw new ArithmeticException("除数不能为 0");
}
return dividend / divisor;
}
// 使用 throws 关键字声明方法可能抛出的异常
public static void checkAge(int age) throws CustomException {
if (age < 0) {
// 当年龄为负数时,抛出自定义异常
throw new CustomException("年龄不能为负数");
}
System.out.println("年龄合法:" + age);
}
public static void main(String[] args) {
try {
// 调用 divide 方法
int result = divide(10, 2);
System.out.println("除法结果:" + result);
// 尝试调用 checkAge 方法,可能会抛出异常
checkAge(25);
// 故意传入负数年龄,触发异常
checkAge(-5);
} catch (ArithmeticException e) {
System.out.println("捕获到算术异常:" + e.getMessage());
} catch (CustomException e) {
System.out.println("捕获到自定义异常:" + e.getMessage());
}
}
}
代码解释
divide
方法中,使用throw
关键字在除数为 0 时手动抛出ArithmeticException
异常。checkAge
方法中,使用throws
关键字声明该方法可能会抛出CustomException
异常。在方法内部,当年龄为负数时,使用throw
关键字抛出该异常。- 在
main
方法中,调用divide
和checkAge
方法,并使用try-catch
块捕获可能抛出的异常。
通过以上示例,可以清楚地看到 throw
和 throws
关键字的区别和使用场景。