java复习-异常

异常

什么是异常

异常指程序运行中出现的不期而至的各种状况:如文件找不到,网络连接失败,非法字符等。

分类:

检查性异常:编译可见

运行时异常:运行可见

错误ERROR:编译检查不到

Error与Exception

Error:

  • 由java虚拟机生成并抛出,一般与代码编写者无关
  • java虚拟机运行错误(Virtual MachineError),虚拟机内存资源不足时会出现OutOfMemoryError。
  • 类定义错误(NoClassDefFoundError)

Exception:

  • RuntimeException(运行时异常)
  • ArrayIndexOutOfBoundsException(数组下标越界)
  • NullPointerException(空指针异常)
  • ArithmeticException(算数异常)
  • MissingResourceException(丢失资源)
  • ClassNotFoundException(找不到类异常)

程序逻辑错误引起的,尽量避免其发生

区别:Error时致命错误,程序无法控制的。JVM会终止,而Exception可以在程序中处理

异常格式

关键词:

try,catch,finally,throw,throws

public class Test {
    public static void main(String[] args) {
        int a =1 ;
        int b =0;
        //捕获多个异常时,要从小到大
        try {//监控异常
            if(b == 0){
                throw new ArithMeticException();//主动抛出异常
            }
            System.out.println(a/b);
        }catch (Exception e) {//catch(想要捕获的异常类型// )捕获异常
            System.out.println("Exception");
        }catch (Throwable e){
            System.out.println("Throwable");
        }finally {//处理善后(可以不要)
            System.out.println("finally");
            e.printStackTrace();//为打印错误信息
        }
    }
    public void a(){
        b();
    }
    public void  b(){
        a();
    }
}

捕获异常的快捷方式:Ctrl +Alt+t

public class Test {
    public static void main(String[] args) {
        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
    //方法中处理不了这个异常。方法上抛出异常
    public void test(int a,int b) throws ArithmeticException{
        if (b == 0){
            throw new ArithmeticException();//主动抛出异常
        }
    }
}

自定义异常

public class Demo1 extends Exception{//自定义异常类
    public Demo1(int detail) {
        this.detail = detail;
    }

    private  int detail;
    public String toString(){
        return  "MyException{"+detail+"}";
    }

}
public class Demo02 {//测试类
    static void test(int a) throws Demo1 {
        System.out.println("输入的值为:"+a);
        if (a>10){
            throw new Demo1(a);
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(1);
        } catch (Demo1 demo1) {
            System.out.println();
        }
    }
}

异常注意

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值