Throws
当异常被抛出时,方法可以选择使用 try/catch 自行处理,或将异常抛给它的调用方(也就是"向上传递")。在本练习中,您将学习如何选择抛出异常,而不是用 try/catch 来处理。
本练习是课程的一部分
Java 的数据类型与异常
练习说明
- 在调用并打印
getScore(3)的代码外层添加一个 try 代码块。 - 添加一个 catch 代码块来处理在
getScore()方法中引发的ArrayIndexOutOfBoundsException。 - 让
getScore(int)抛出ArrayIndexOutOfBoundsException,而不是在方法内用 try/catch 处理该异常。
交互式实操练习
通过完成这段示例代码来试试这个练习。
package exceptions;
public class ThrowingExample {
public static int[] scores = { 75, 97, 83 };
public static void main(String[] args) {
// Add a try block
____ {
int lastScore = getScore(3);
System.out.println("Last score:" + lastScore);
// Catch the exception thrown by getScore(int)
} ____ (____ e) {
System.out.println("Tried to access non-existent score");
}
}
// Throw ArrayIndexOutOfBoundsException
public static int getScore(int index) ____ ____ {
return scores[index];
}
}