一招搞定Java中的异常Exception和错误Error

Java中的Exception异常、Error错误

知识点

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

案例代码

案例一:对象点方法的应用

package com.oop.exception;

public class Demo01 {
    public static void main(String[] args) {
        new Demo01().a();//new对象点方法

    }
    public void a(){
        System.out.println("在吗?");

    }

}

运行结果: 在吗?

案例二:try、catch的应用

package com.oop.exception;

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        //假设要捕获异常,要小到大,即:Throwable>Exception>Error
        try {//try监控区域
            System.out.println(a/b);//结果为Exception
            //new Test().a();//new对象点方法就可以//结果为Error
            //Throwable>Exception>Error 其中如果有多个catch,那throwable要写在最后面,然后在是
            //Exception 接着Error.然后每个程序最多只能捕获一个catch
        }catch(Error e){//catch(想要捕获的异常类型!)捕获异常
            System.out.println("Error");
        }
        catch (Exception e){
            System.out.println("Exception");

        }
        catch(Throwable t){
            System.out.println("Throwable");

        } finally{//处理善后工作
            System.out.println("finally");
        }
        //finally 可以不要finally, 但是像I/O流 ,资源类的用完要关闭就放在finally里面。
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}

案例三:throw抛出异常

package com.oop.exception;

public class Test1 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            if(b==0){//主动抛出异常 throw  和throws 不一样
                throw new ArithmeticException();//动抛出异常 throw
            }
            System.out.println(a/b);//快捷键ctrl+alt+T可以选择
        } catch (Exception e) {
            e.printStackTrace();//打印错误的栈信息
        } finally {
        }
    }
}

案例四:throw、throws抛出异常的区别

package com.oop.exception;

public class Test2 {
    public static void main(String[] args) {
        try {
            new Test2().test2(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();//快捷键Ctrl+alt+T
        }

    }
    //假设在方法中处理不了这个异常,可以在方法上抛出异常,用throws
    public void test2(int a,int b) throws ArithmeticException{
        if(b==0){//throw  throws
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值