public class MakeException {
/*自定义异常:
* 1.建立异常类(要求类名见名知意)
* 2.异常类继承Exception(非运行时异常),继承RuntimeException(运行时异常)
* 3.如果需要异常详细描述,定义构造器,调用super(message);
*抛出自定义异常: throw 自定义异常类的对象
*1.异常处理的方法:
*1.1将异常抛出给上级处理:
*方法名() throws 异常类名{}
*throws 的异常类声明,要保证无论抛出哪一个异常对象,都存在该异常类自己或者其父类被声明
*/
public static void main(String[] args) throws Exception
{
GirlHome gh = new GirlHome("唐川洋",'女',26);
gh.intoHome();
}
}
class GirlHome {
public String name;
public char sex;
public int age;
public GirlHome(String name,char sex,int age)
{
super();
this.name = name;
this.sex = sex;
this.age = age;
}
//如果发现进入者是男的,那么抛出性别异常
public void intoHome() throws SexOutException,AgeOutException{
if(sex!='女'){
SexOutException se = new SexOutException(name+"你不是女的,滚!!!");
throw se;
}
if(age>25){
throw new AgeOutException(name+"你的年龄太大了,滚!!!!");
}
System.out.println(name+"开心的进入了宿舍");
}
public void demo()throws Exception{}
}
public String name;
public char sex;
public int age;
public GirlHome(String name,char sex,int age)
{
super();
this.name = name;
this.sex = sex;
this.age = age;
}
//如果发现进入者是男的,那么抛出性别异常
public void intoHome() throws SexOutException,AgeOutException{
if(sex!='女'){
SexOutException se = new SexOutException(name+"你不是女的,滚!!!");
throw se;
}
if(age>25){
throw new AgeOutException(name+"你的年龄太大了,滚!!!!");
}
System.out.println(name+"开心的进入了宿舍");
}
public void demo()throws Exception{}
}
class AgeOutException extends Exception{
public AgeOutException(String message){
super(message);
}
}
public AgeOutException(String message){
super(message);
}
}
class SexOutException extends Exception{
public SexOutException(String message){
super(message);
}
public void demo(){
System.out.println("爱啦啦阿拉");
}
}
public SexOutException(String message){
super(message);
}
public void demo(){
System.out.println("爱啦啦阿拉");
}
}
更多java知识请访问:
How2J 的 Java教程