1. throws关键字
throws关键字通常应用在声明方法时,用来指定可能抛出的异常。多个异常可以使用逗号隔开。当在主函数中调用该方法时,如果发生异常,就会将异常抛给指定异常对象。
public class ThrowsTest {
//定义方法并抛出NegativeArraySizeException异常
public static void testThrows() throws NegativeArraySizeException {
int[] arr = new int[-3]; //创建不合法数组
}
public static void main(String[] args) {
try {
testThrows(); //调用testThrows()方法
} catch (NegativeArraySizeException e) {
System.out.println("捕捉到throws抛出的异常!");
}
}
}
输出:捕捉到throws抛出的异常!
2. throw关键字
throw关键字通常用在方法体中,并且抛出一个异常对象。程序在执行到throw语句时立即停止,它后面的语句都不执行。通过throw抛出异常后,如果想在上一级代码中来捕获并处理异常,则需要在抛出异常的方法中使用throws关键字在方法声明中指明要抛出的异常;如果要捕捉throw抛出的异常,则必须使用try—catch语句。
public class ThrowTest {
private static class MyException extends Exception {
String message;
public MyException(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
public static void testThrow() throws NegativeArraySizeException {
try {
throw new MyException("这是我自定义的异常!");
} catch (MyException e) {
System.out.println("捕捉到throw抛出的异常:" + e.getMessage());
} finally {
int[] arr = new int[-3]; // 将异常返回给上一级方法
}
}
public static void main(String[] args) {
try {
testThrow();
} catch (NegativeArraySizeException e) {
System.out.println("捕捉到throws抛出的异常!");
}
}
}
输出:
捕捉到throw抛出的异常:这是我自定义的异常!
捕捉到throws抛出的异常!
本文介绍了Java中的异常处理关键字`throws`和`throw`。`throws`常用于方法声明,指定可能抛出的异常,不强制当前方法处理,而是由调用者处理。`throw`则在方法体中抛出一个异常对象,导致程序中断,后续代码不会执行。使用`throw`抛出异常后,需在方法声明中使用`throws`指定异常,或者在上层代码中用try-catch捕获。
3458

被折叠的 条评论
为什么被折叠?



