Java面向对象——自定义异常

1.传参

package Test_Prtice01;

public class Person1 {
    
    
    String name;
    String gender;

    public Person1(String name,String gender){
    
    
        this.name=name;
        this.gender=gender;
    }
}

2.条件

package Test_Prtice01;

public class Person2 {
    
    
    public void nan(Person1 p)throws GenderException{
    
    
        if (p.gender.equals("男")){
    
    
            System.out.println("欢迎光临");
        }else {
    
    //来了个女生
            //需要一个异常
            throw new GenderException("性别不对,这里是男生洗澡的地方");
        }
    }
}

3.自定义异常

package Test_Prtice01;

public class GenderException extends Exception {
    
    //自己定义的异常必须要继承Exception或者
    public GenderException(String msg){
    
    
        super(msg);//调用父类的构造方法 Exception(msg)
    }
}

4.主程序(程序的入口)

package Test_Prtice01;

public class Test {
    
    
    public static void main(String[] args) throws GenderException{
    
    
        Person1 p1=new Person1("杜俊风","女");
        Person1 p2=new Person1("俊风","男");
        Person2 p3=new Person2();
        p3.nan(p2);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_62491934/article/details/124592617