自定義異常類,當調用Player類的play方法時,如果參數大于10 則報異常
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 Test03 {
public static void main(String[] args) {
Player player = new Player();
try {
player.play(13);
} catch (NoThisSongException e) {
System.out.println("異常資訊為: "+e.getMessage());
}
}
}
運作結果:
異常資訊為: 您播放的歌曲不存在