关于异常的一些练习

前言:

        大家好,这次我给大家分享一些关于异常的运行结果类型题,做题思路和分析为了方便大家阅读都写在注释里了。


目录

第一题:

第二题:

第三题:


第一题:

class Exc0 extends Exception {
}

class Exc1 extends Exc0 {
}

public class LianXi6 {
    public static void main(String[] args) {
        try {
            throw new Exc1();
        } catch (Exc0 e) {//将小网放前面,大网放后面就能捕捉漏小网之鱼
            System.out.println("Exc0");
        } catch (Exception e) {//Exception好比一张大网,将所有异常、包括它的子类异常都捕捉了,如果小网放后面捕捉Exc1异常就没有意义了。
            System.out.println("Exception");
        }
    }
}

第二题:

class Test {
    public static String output = "";

    public static void foo(int i) {
        try {
            if (i == 1) {
                throw new Exception();
            }
            output += "1";//1
        } catch (Exception e) {
            output += "2";//3//13423
            return;
        } finally {
            output += "3";//13//1342
        }
        output += "4";//134
    }

    public static void main(String args[]) {
        foo(0);
        System.out.println(output);//134
        foo(1);//output是全局变量,第一个foo方法改变了output的值为134.
        System.out.println(output);//13423
    }
}

第三题:

public class ReturnExceptionDemo {
    static void methodA() {
        try {
            System.out.println("进入方法A");//输出
            throw new RuntimeException("制造异常");//抛出异常前执行finally语句,之后输出
        } finally {
            System.out.println("用A方法的finally");//输出
        }
    }

    static int methodB() {
        try {
            System.out.println("进入方法B");//输出
            // throw new Exception();
            return 1;//返回之前执行finall语句,然后返回值为1
        } catch (Exception e) {
            return 3;
        } finally {
            System.out.println("调用B方法的finally");//输出
            // return 2;
        }
    }

    public static void main(String[] args) {
        try {
            methodA();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        int i = methodB();
        System.out.println(i);//输出
    }

}

所以该题的运行结果为:

进入方法A
       用A方法的finally
    制造异常
       输出异常信息
       进入方法B
       调用B方法的finally
       1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值