JAVA中catch多个异常处理方案

如何处理异常
1)一个一个处理
每一个代码都try...catch...
2)变形格式
try...catch..catch
注意事项:
针对多个异常处理的时候,只能大的异常类名放在最后面进行处理,不能放在最前面
JDK7以后:有一种的新的处理方式: (源码里面会看到,看懂格式即可)

  • try{
    
  •     可能出现的代码;
    
  • }catch(异常类名1 | 异常类名2 | 异常类名3 变量名){
  •     处理异常;
    
  • }
public class ExceptionDemo3 {
    public static void main(String[] args) {
//      method1();
        method2();
    }
    //一个try多个catch进行处理
    private static void method2() {
        try {
            int a=10;
            int b=5;
            int arr[]= {3,1,5};
            System.out.println(a/b);
            System.out.println(arr[2]);
            ArrayList<String>list=new ArrayList<String>();
            list.add("hello");
            list.add("qwe");
            list=null;
            for(String s:list) {//对于增强for遍历集合不能为空
                System.out.println(s);
            }
        }catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("访问了数组不存在的角标");
        }catch(ArithmeticException e) {
            System.out.println("除数不能为0");
        }catch(Exception d) {
            System.out.println("程序出问题了");
        }
        System.out.println("over");
    }
    /*
    //情况1:针对可能出现问题的代码一个一个处理
    private static void method1() { 
        //定义两个变量
        try {
            int a=10;
            int b=0;
            System.out.println(a/b);
        }catch(ArithmeticException e) {
            //手动处理
            System.out.println("除数不能为0");
        }
        try {
            //定义一个数组
            int arr[]= {3,1,5};
            System.out.println(arr[3]);
        }catch(ArrayIndexOutOfBoundsException e) {
            //手动处理
            System.out.println("访问了数组不存在的角标");
        }
    }   
    */
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值