抛出异常throws和throw的方法

代码块:
package edu.xucd;

public class Demo04 {
/*
调用者的异常类型要比被调用者的异常类型“大”Exception>=SexException
*/
public static void main(String[] args) throws Exception{
setSex("变性人");
}
public static void setSex(String sex)throws SexException{//声明有可能出现的异常
if (!sex.equals("男")||sex.equals("女")){
throw new SexException("性别既不是男也不是女");
}
}
}

测试块:
package edu.xucd;
/*
1 需要继承自Excetion
2需要复写无参构造方法
3 需要复写message参数的构造方法
*/

public class SexException extends Exception{
public SexException(){

}
public SexException(String message){
    super(message);
    System.out.println("性别异常");
}

}

你可能感兴趣的:(抛出异常throws和throw的方法)