异常处理

处理异常的几种格式

try...catch     try...catch...finally     try...finally

如何正确的处理异常

1.正常情况三条信息都打印。

public static void main(String[] args){
    
    System.out.println("【1】程序开始执行");
    System.out.println("【2】程序执行中" + 10/2);
    System.out.println("【3】程序始执完毕");
}

 2.程序异常情况,程序中10/0出现异常,第三条信息不打印。

public static void main(String[] args){
    
    System.out.println("【1】程序开始执行");
    System.out.println("【2】程序执行中" + 10/0);
    System.out.println("【3】程序始执完毕");
}

3.捕获异常

public static void main(String[] args){
    
    System.out.println("【1】程序开始执行");
    try{
        System.out.println("【2】程序执行中" + 10/0);
    }catch(ArithmeticException e){
        System.out.println("异常信息:" + e);
    }
    System.out.println("【3】程序始执完毕");
}

4.多次异常捕获,异常分很多中,每个程序出现的异常也不一样,d2为0时就会抛出ArithmeticException异常,当参数不是数字时就会初出现NumberFormatException异常,当参数为null时则会抛出NullPointerException。

public static void main(String[] args){
     int d1= Integer.valueOf(args[0]);
     int d2= Integer.valueOf(arga[1]);
    
    System.out.println("【1】程序开始执行");
    try{
        System.out.println("【2】程序执行中" + d1/d2);
    }catch(ArithmeticException e){
        System.out.println("异常信息:" + e);
    }catch(NumberFormatException e){
        e.printStackTrace();
    }catch(NullPointerException e){
        e.printStackTrace();
    }
    System.out.println("【3】程序始执完毕");
}

5.异常处理流程

1.在程序执行之中才会产生异常,而一旦程序产生了异常就会自动实例化异常对象

2.如果程序没有进行异常处理,那么程序就会采用JVM默认的异常处理方式,首先打印异常信息, 然后中断程序。

3.程序中存在异常捕获,那么就需要按照顺序去排查异常与捕获的是否匹配,然后继续执行finally代码块,处理其他代码块内容,打印异常。

6.所有异常父类Execption,程序在执行时会出现那些异常我们也不知道(如果知道也不用去捕获异常),所以当我们知道程序会出现什么异常时就需要用到异常的父类。当然Execption应该放在所有异常执行捕获。

public static void main(String[] args){
     int d1= Integer.valueOf(args[0]);
     int d2= Integer.valueOf(arga[1]);
    
    System.out.println("【1】程序开始执行");
    try{
        System.out.println("【2】程序执行中" + d1/d2);
    }catch(ArithmeticException e){
        System.out.println("异常信息:" + e);
    }catch(NumberFormatException e){
        e.printStackTrace();
    }catch(NullPointerException e){
        e.printStackTrace();
    }catch(Execption e){
        e.printStackTrace();
    }
    System.out.println("【3】程序始执完毕");
}

7.throws抛出异常。

class Operation{
    //抛出Exception异常
    public static return divide(String x,String y)throws Exception{
        int d1 = Integer.parseInt(x);
        int d2 = Integer.parseInt(y);
        return d1 / d2;
    }
}

public class Test{
    //主方法中捕获异常
    public static void main(String[] args){
        try{
            Operation.devide(10,0);
        }catch(Exception e){
             e.printStackTrace();
        }
    }
}

8.throw方法体内抛出异常

public static void divide(int x){
       if(x > 10){
           throw new IllegalArgumentException();
       }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值