GirlFriendNotFoundException异常是怎样处理的?


如果说要去创造这个异常,那么我们的JAVA程序里,肯定是继承Exception去处理,所有我们可以先实现一个自己的Exception

/**
* GirlFriendNotFoundException
*
* @author LGL
*
*/
class GirlFriendNotFoundException extends Exception {

private String msg;

public GirlFriendNotFoundException(String msg) {
this.msg = msg;
}

@Override
public String getMessage() {
// TODO Auto-generated method stub
return msg;
}
}

这里只是重写了getMessage方法,反馈我们的异常信息,那我们来定义一个方法

class Demo {
int dev(int age) throws GirlFriendNotFoundException {
if (a < 18) {
// 手动通过throw关键字抛出自定义异常对象
throw new GirlFriendNotFoundException("Girl Friend Not Found !!!");
}
return age;
}
}

我们可以传递一个参数age,如果女朋友的年龄小于18就抛出异常,那我们来测试一下

/**
* 自定义异常
*
* @author LGL
*
*/
public class CustomException {
public static void main(String[] str) {
Demo d = new Demo();
try {
d.dev(16);
} catch (GirlFriendNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

哈哈,我们女朋友还只有16岁,那我们肯定就异常了

GirlFriendNotFoundException异常是怎样处理的?_ide

此篇纯属娱乐,哈哈,有兴趣的加群:555974449