自定义异常类
- 编译期异常类: class 异常类名 extends Exception{}
- 运行期异常: class 异常类名 extends RuntimeException{}
- 类中添加两个构造方法:一个默认消息的构造方法,一个是指定消息的构造方法
代码示例:
自定义一个游戏输赢异常类
public class Not_PlayGame_Win extends Exception{
//默认消息
public Not_PlayGame_Win() {
super("系统维护中...");
}
//指定消息
public Not_PlayGame_Win(String message) {
super(message);
}
}
自定义一个判断类
public class Battle {
public static void gameBattle(int win, int lose)throws Not_PlayGame_Win{
if (win>lose){
throw new Not_PlayGame_Win("您好棒,遥遥领先");
}else if(win<lose) {
throw new Not_PlayGame_Win("您差远了。。。");
}else {
throw new Not_PlayGame_Win("这把平局");
}
}
}
运行结果:
public class GameTest {
public static void main(String[] args) {
// 打游戏赢了几把
int win = 150;
// 打游戏输了几把
int lose = 15;
try {
gameBattle(win,lose);
} catch (Not_PlayGame_Win e) {
System.err.println(e.getMessage());
}
}
}
输出:您好棒,遥遥领先
标签:JAVA,自定义,16,PlayGame,Win,class,win,public From: https://blog.csdn.net/xudahai513/article/details/145095481