Java练习6:自定义一个异常类NoThisSongException和Player类

作者说:

这个实验用到了自定义异常类的知识,练习了throws、throw、try...catch的使用方法。

实验的要求还是比较详细的,比较好完成。

一、实验要求

二、运行效果截图

1.输入的数据符合要求

2.输入的数据不符合要求

三、代码示例

import java.util.Scanner;

public class Test6 {
    public static void main(String[] args) {
        Player p=new Player();//创建Player对象p。
        Scanner s=new Scanner(System.in);
        System.out.println("");
        System.out.println("author---Henan University.software engineering.李思佳");
        System.out.print("请输入您想要播放的歌曲序号(1~10):");
        try{
            int a=s.nextInt();
            p.play(a);
            System.out.println("您现在所播放的歌曲序号为:"+a);
        }catch(NoThisSongException e){
            System.out.println(e.getMessage());
        }
    }
}

class NoThisSongException extends Exception{//自定义异常类NoThisSongException,继承Exception类。
    public NoThisSongException(){//类中的无参构造方法。
        super();
    }
    public NoThisSongException(String s){//类中的String参数构造方法。
        super(s);
    }
}
class Player{//自定义Player类
    public void play(int index) throws NoThisSongException{//play()方法中使用了自定义异常。
        if(index>10||index<=0) {//抛出NoThisSongException异常。
            throw new NoThisSongException("您播放的歌曲不存在哦!");//调用了自定义异常类中的有参构造方法。
        }
    }
}

 

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值