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

本文介绍如何在Java中自定义异常类NoThisSongException,该异常用于表示播放不存在的歌曲。通过Player类的play()方法演示了如何抛出和捕获自定义异常,以及如何在异常对象中传递错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

  1. NoThisSongException 继承 Exception 类,类中有一个无参和一个接收一个 String 类型参数的 构造方法,构造方法中都使用 super 关键字调用父类的构造方法。
  2. Player 类中定义一个 play(int index) 方法,方法接收一个 int 类型的参数,表示播放歌曲的索引,当 index>10 时,play()方法用 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 Test05 {
    public static void main(String[] args) {
        Player player = new Player();

        try {
            player.play(13);
        } catch (NoThisSongException e) {
            System.out.println("异常信息为: " + e.getMessage());
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烟敛寒林o

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值