Java自定义一个异常类NoThisSongException和Player类

2022-07-27,,,

作者说:

这个实验用到了自定义异常类的知识,练习了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("您播放的歌曲不存在哦!");//调用了自定义异常类中的有参构造方法。
        }
    }
}

 

本文地址:https://blog.csdn.net/m0_52229815/article/details/109864508

《Java自定义一个异常类NoThisSongException和Player类.doc》

下载本文的Word格式文档,以方便收藏与打印。