任务描述:自定义一个异常类NoThisSoundException和Player类,在Player类的player()方法中使用自定义异常。
定义异常类NoThisSoundException继承自Exception类,类中有一个无参构造方法、一个有参构造方法,构造方法中都使用super关键字调用父类的构造方法。
Player类中定义一个player(int index)方法,当index<=10的时候,输出“正在播放第× ×首歌曲”;当index>10时,抛出NoThisSoundException异常,输出的异常信息为:“您播放的歌曲不存在”。
在测试类中创建Player对象,并调用player()方法,捕获并处理该方法可能产生的异常。
// 自定义播放异常类
public class NoThisSongException extends Exception {
public NoThisSongException() {
super();
}
public NoThisSongException(String message) {
super(message);
}
}
// 播放歌曲的类
public class Player {
public void play(int index) throws Exception {
if(index>10)
throw new NoThisSongException("您播放的歌曲不存在");
else
System.out.println("正在播放第"+index+"首歌曲");
}
}
// 测试类
public class PlayerTest {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
Player p1=new Player();
int index;
index=scan.nextInt();
try {
p1.play(index);
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
}