java中try...catch处理异常

public class TryCatchStu {
 /*try catch:自己处理异常
  *try{
  * 可能出现异常的代码
  *}catch(异常类名A e){
  * 如果出现了异常类A类型的异常,那么执行该代码
  *}...(catch可以有多个)
  *finally{
  * 最终肯定必须要执行的代码(例如释放资源的代码)
  *}
  *代码执行的顺序:
  *1.try内的代码从出现异常的那一行开始,中断执行
  *2.执行对应的catch块内的代码
  *3.继续执行try catch 结构之后的代码
  *注意点:
  *1.如果catch内的异常类存在子父类的关系,那么子类应该在前,父类在后
  *2.如果finally中有return语句,那么最后返回的结果肯定以finally中的返回值为准
  *3.如果finally语句中有return,那么没有被处理的异常将会被吞掉
  *重写的注意点:
  *1.儿子不能比父亲的本事大
  *2.儿子要比父亲开放
  *3.儿子不能比父亲惹更大的麻烦(子类的异常的类型不能是父类的异常的父类型)
  *异常类Api:
  *1.getMessage():获取异常描述信息字符串
  *2.toString():返回异常类的包路径和类名和异常描述信息字符串
  *3.printStackTrace():除了打印toString的信息外,还要打印堆栈信息
  */
 public static void main(String[] args)
 {
  System.out.println(demo());
 }
 public static int demo(){
  GirlHome gh = new GirlHome("小陈陈",'男',28);
  try{
   gh.intoHome();
   System.out.println("进入了女生宿舍");
   return 0;
  }catch(SexOutException e){
   //System.out.println("出现了异常");
   //System.out.println(e);
   e.demo();
   e.printStackTrace();
  }catch (AgeOutException e) {
   // TODO: handle exception
  }finally{
   System.out.println("我必须被执行");
  }
  return 1;
  //System.out.println("愉快的一天结束啦");
 }
}

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{}
}

class SmallGirlHome extends GirlHome{

 public SmallGirlHome(String name, char sex, int age)
 {
  super(name, sex, age);
  // TODO Auto-generated constructor stub
 }
 @Override
 public void intoHome() throws SexOutException,AgeOutException
 {
  
 }
 public void demo()
 {
  
 }

class AgeOutException extends Exception{
 public AgeOutException(String message){
  super(message);
 }
}
 class SexOutException extends Exception{
 public SexOutException(String message){
  super(message);
 }
 public void demo(){
  System.out.println("爱啦啦阿拉");
 }
}
 
}
更多java知识请访问: How2J 的 Java教程

  • 13
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值