Java-异常机制处理RuntimeExcpetion

 

package com.it;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test01 {
    public static void main(String[] args) {
        test03();
    }

    public static void test01(){
        System.out.println("111");
        int a = 1/0;
        System.out.println("222");
    }
    public static void test02(){
        System.out.println("111");
//        快捷键alt+command+t
        try {
            int a = 1/0;
        } catch (Exception e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
        }

        System.out.println("222");
    }

    /**
     * RuntimeException需要程序员做逻辑处理
     */
    public static void test03(){
        int a =1;
        int b = 0;
//        ArithmeticException by Zero
//        System.out.println(a/b);
        if (b!=0){
            System.out.println(a/b);
        }

//        空指针异常 NullPointerException
        String str = null;
        if(str!=null){
            System.out.println(str.charAt(3));
        }

//        数字格式化异常 NumberFormatException
        String str1 = "abc123";
//        System.out.println(Integer.parseInt(str1));
        Pattern p = Pattern.compile("^\\d+$");
        Matcher m = p.matcher(str1);
        if(m.matches()){
            System.out.println(Integer.parseInt(str1));
        }else{
            System.out.println("数字格式不对");
        }


//        数组下标越界 ArrayIndexOutOfBoundsException
        int[] arr = new int[5];
        int f = 3;
        if (f>=0&&f<arr.length){
            System.out.println(arr[f]);

        }

//  类型转化异常 ClassCastException
        Animal A = new Dog();
        if (A instanceof Cat){
            Cat C = (Cat)A;
        }
    }
}
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值