示例 1 : 创建自定义异常
一个英雄攻击另一个英雄的时候,如果发现另一个英雄已经挂了,就会抛出enemyheroisdeadexception
创建一个类enemyheroisdeadexception,并继承exception
提供两个构造方法
class enemyheroisdeadexception extends exception{ public enemyheroisdeadexception(){ } public enemyheroisdeadexception(string msg){ super(msg); } }
示例 2 : 抛出自定义异常
在hero的attack方法中,当发现敌方英雄的血量为0的时候,抛出该异常
在外部调用attack方法的时候,就需要进行捕捉,并且捕捉的时候,可以通过e.getmessage() 获取当时出错的具体原因
package charactor; public class hero { public string name; protected float hp; public void attackhero(hero h) throws enemyheroisdeadexception{ if(h.hp == 0){ throw new enemyheroisdeadexception(h.name + " 已经挂了,不需要施放技能" ); } } public string tostring(){ return name; } class enemyheroisdeadexception extends exception{ public enemyheroisdeadexception(){ } public enemyheroisdeadexception(string msg){ super(msg); } } public static void main(string[] args) { hero garen = new hero(); garen.name = "盖伦"; garen.hp = 616; hero teemo = new hero(); teemo.name = "提莫"; teemo.hp = 0; try { garen.attackhero(teemo); } catch (enemyheroisdeadexception e) { // todo auto-generated catch block system.out.println("异常的具体原因:"+e.getmessage()); e.printstacktrace(); } } }
如对本文有疑问, 点击进行留言回复!!
集合框架——Map、泛型以及Collection算法常用方法
Elasticsearch 升级 7.x 版本后,我感觉掉坑里了
Mybatis的插件运行原理以及如何编写一个Mybatis的插件
网友评论