自定义一个异常类 NoThisSoundException 和 Player 类,在 Player 的 play()方法中使用自定义异常, 要求如下:
- NoThisSongException 继承 Exception 类,类中有一个无参和一个接收一个 String 类型参数的 构造方法,构造方法中都使用 super 关键字调用父类的构造方法。
- Player 类中定义一个 play(int index) 方法,方法接收一个 int 类型的参数,表示播放歌曲的索引,当 index>10 时,play()方法用 throw 关键字抛出 NoThisSongException 异常,创建异常对象时,调用有参的构造方法,传入“您播放的歌曲不存在” 。
- 在测试类中创建 Player 对象,并调用 play()方法测试自定义的 NoThisSongException 异常,使 用 try…catch 语句捕获异常, 调用 NoThisSongException 的 getMessage()方法打印出异常信息。
class NoThisSongException extends Exception {
public NoThisSongException() {
super();
}
public NoThisSongException(String message) {
super(message);
}
}
class Player {
public void play(int index) throws NoThisSongException {
if (index > 10) {
throw new NoThisSongException("您播放的歌曲不存在");
}
System.out.println("正在播放歌曲");
}
}
public class Test05 {
public static void main(String[] args) {
Player player = new Player();
try {
player.play(13);
} catch (NoThisSongException e) {
System.out.println("异常信息为: " + e.getMessage());
}
}
}