直接继承Exception或者RuntimeException来实现自定义异常
public class Person {
String name;
String gender;
public Person(String name,String gender){
this.name=name;
this.gender=gender;
}
}
public class ZaoTangZi {
public void nan (Person p) throws GenderException{
if(p.gender.equals("男")){
System.out.println("欢迎光临");
}else{//来了个女的
//需要抛出一个异常
throw new GenderException("性别不对,这里是男澡堂子");
}
}
}
public class GenderException extends Exception{//自己定义的异常必须要继承Exception或者RuntimeException
public GenderException(String msg){
super(msg);//调用父类的构造方法,Exception(msg)
}
}
public class Test {
public static void main(String[] args) throws GenderException{
Person p1=new Person("张无忌","男");
Person p2=new Person("赵敏","女");
ZaoTangZi ztz=new ZaoTangZi();
ztz.nan(p2);
}
}
运行结果
Exception in thread "main" GenderException: 性别不对,这里是男澡堂子
at ZaoTangZi.nan(ZaoTangZi.java:8)
at Test.main(Test.java:9)
Process finished with exit code 1
(自主学习,侵权可删)