您的位置:首页 > 其它

自定义一个异常类NoThisSoundException和Player类,在Player的play()方法中使用自定义异常

2017-09-30 13:43 603 查看
7、自定义一个异常类NoThisSoundException和Player类,在Player的play()方法中使用自定义异常
1)NoThisSongException继承Exception类,类中有一个无参和一个接收一个String类型参数的构造方法,构造方法中都使用super关键字调用父类的构造方法。
2)Player类中定义一个play(int index)方法,方法接收一个int类型的参数,表示播放歌曲的索引,当index>10时,paly()方法用throw关键字抛出NoThisSongException异常,创建异常对象时,调用有参的构造方法,传入“您播放的歌曲不存在”。
3)在测试类中创建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 Test03 {
public static void main(String[] args) {
Player player = new Player();
try {
player.play(13);
} catch (NoThisSongException e) {
System.out.println("异常信息为: "+e.getMessage());
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐