原 自学JVAVA---(31)--(内功心法【29】)异常

异常
【小城贝尔】
程序运行抛异常,多少小猿曾断肠。
撕心裂肺心好凉,额头发际又上扬。
运行一场逻辑忙,真心让人好抓狂。
检查异常警笛响,抓住处理或上扬。

exception:列外异常
java采用面向对象的方式处理异常
**1,**抛出异常 ,运行发生异常的时候终止运行序列将异常性息生成一个对象交给jre
**2,**jre得到异常后开始查找代码处理异常
在这里插入图片描述

public class ExceptionDemo {
    public static void main(String[] args) {
        ExceptionDemo ed = new ExceptionDemo();
        try {
            ed.method();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("无论是否出错都会执行");
        }
    }
    
    public void method () throws  Exception{
        //抛出异常
        throw new Exception();
    }
}

常见异常

//空指针
        Integer ins = null;
        ins.toString();
Exception in thread "main" java.lang.NullPointerException

 //类型转换
 Animal animal = (Animal) new Cut();
 AlwaysClass.Cut cannot be cast to AlwaysClass.Animal

 //数组越界
 int[] arr = {1,2,3};
  int i = arr[6];
java.lang.ArrayIndexOutOfBoundsException: 6

自定义异常

//自定义异常继承Exception
public class ExceptionMyself extends Exception {
   public ExceptionMyself(String message){
       super(message);
   }
}
class Test{
    public static void main(String[] args) {
       /*
       ExceptionMyself e =new ExceptionMyself("自定义的异常");
       e.printStackTrace();
       */
       Test t = new Test();
       try {
       //AlwaysClass.ExceptionMyself: 被零除了哦
	  //at AlwaysClass.Test.division(ExceptionMyself.java:25)
	  //at AlwaysClass.Test.main(ExceptionMyself.java:16)
           t.division(2,0);
       }catch (ExceptionMyself e){
           e.printStackTrace();
       }

    }
    
    //抛出了自定义异常的方法
    public void division(int i , int b) throws ExceptionMyself{
        if (b == 0){
            throw  new ExceptionMyself("被零除了哦");
        }else{
            int c = i/b;
            System.out.println("result :  "+c);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值