异常与处理

异常

异常包括错误Error和异常Exception。

Error

虚拟机运行错误,如栈溢出。无法处理。

Exception

一般由于程序逻辑出错导致。可以处理。

异常处理

捕获异常

public class Demo01 {
    public static void main(String[] args) {
        int a = 1,b = 0;
        //选中要捕获的代码,Ctrl + Alt + T,快捷键,快速生成try-catch
        try {//捕获异常的代码
            System.out.println(a/b);
        }catch (ArithmeticException e){//可能出现的异常
            System.out.println("除数无法为0");//异常出现时,不执行异常代码,执行这条代码
        }catch (Throwable t){//异常类型由小到大
            System.out.println("error");
        }finally {//最终无论是否出现异常,都会执行的代码
            System.out.println("end");
        }
    }
}

主动抛出异常

public class Demo02 {
    public static void main(String[] args) {
        int a = 1,b = 0;
        try {
            if (b == 0){
                throw new ArithmeticException();//主动抛出异常
            }
            System.out.println(a/b);
        } catch (Exception e) {
            System.exit(1);//程序结束
            e.printStackTrace();
        } finally {
        }
    }
}

抛出异常

public class Demo02 {
    public static void main(String[] args) {
        try {
            new Demo02().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
    public void test(int a,int b) throws ArithmeticException{//抛出异常
        if (b == 0){
            throw new ArithmeticException();//主动抛出异常
        }
        System.out.println(a/b);
    }
}

自定义异常

public class MyException extends Exception{//继承异常
    private int detail;

    public MyException(int a) {//构造器
        detail = a;
    }

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
public class Test {
    public static void test(int a) throws MyException {
        if (a>10){
            throw new MyException(a);//主动抛出
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            System.out.println("MyException=>"+e);//打印异常信息,自定义里面的toString内容
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值