A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© haohanlinyu 中级黑马   /  2014-6-30 22:48  /  914 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 haohanlinyu 于 2014-7-1 21:27 编辑

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

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马