自定义一个异常类 NoThisSoundException 和 Player 类
有问必答
eclipse
自定义一个异常类 NoThisSoundException 和 Player 类,在 Player 的 play()方法中使用自定义异常,要求如下:
数的构造方法,构造方法中都使用 super 关键字调用父类的构造方法。
的索引,当 index>10 或 index<0 时,paly()方法用 throw 关键字抛出 NoThisSongException
异常,创建异常对象时,调用有参的构造方法,传入“您播放的歌曲不存在”。
常,使用 try…catch 语句捕获异常,调用 NoThisSongException 的 getMessage()方法打印出
异常信息。finally 部分打印出“正在播放歌曲”。
或“正在播放歌曲”,通过“播放”按钮播放歌曲。
题目意思说的很清楚,你一步步按照题目意思创建类、方法有问题、异常再问吧
public class Main {
public static void main(String[] args) {
Player player = new Player();
try {
player.play(20);
}catch (NoThisSoundException e){
System.out.println(e.getMessage());
}finally{
System.out.println("正在播放歌曲");
}
}
}
class Player {
public void play(int index) throws NoThisSoundException {
if (index > 10 || index < 0){
throw new NoThisSoundException("您播放的歌曲不存在");
}else{
System.out.println("播放歌曲 " + index);
}
}
}
class NoThisSoundException extends Exception{
private String message;
public NoThisSoundException(){
super();
}
public NoThisSoundException(String message){
super();
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
Player.java
package com.yw.test3;
public class Player
{
public Player()
{
}
public void play(int index) throws NoThisSoundException
{
if (index > 10 || index < 0){
throw new NoThisSoundException("您播放的歌曲不存在");
}else{
System.out.println("播放歌曲 " + index);
}
}
public static void main(String [] args){
Player player = new Player();
try
{
player.play(1);
player.play(11);
}catch (NoThisSoundException e){
System.out.println(e.getMessage());
}finally{
System.out.println("正在播放歌曲");
}
}
}
NoThisSoundException.java
package com.yw.test3;
public class NoThisSoundException extends Exception{
private String message;
public NoThisSoundException(){
super();
}
public NoThisSoundException(String message){
super();
this.message = message;
}
@Override
public String getMessage()
{
return message;
}
}