jdk16全面学习之jls的第十一章Exceptions

jdk16全面学习之jls的第十一章Exceptions

  异常在java中是很常见的,也是可以直接进行处理的.主要分为受检异常和运行时异常.
  受检异常的捕获是按照子类和父类的先后顺序进行的,而运行时异常也是如此,只是更加灵活而已.

1 受检异常

  调试的代码为:

package com.company;

import java.io.FileNotFoundException;
import java.io.IOException;

public class Main1 {
    public static void main(String[] args) {
        try {
            throw new FileNotFoundException();
        } catch (IOException ioe) {
            System.out.println("catched the IOException 1");
        }

        try {
            throw new FileNotFoundException();
        } catch (FileNotFoundException fnfe) {
            System.out.println("catched the FileNotFoundException");
        }

        try {
            m();
        } catch (FileNotFoundException fnfe) {
            System.out.println("catched the FileNotFoundException in m");
        } catch (IOException ioe) {
            System.out.println("catched the IOException in m");
        } catch (Throwable t) {
            System.out.println("catched the Throwable in m");
        }
    }

    static void m() throws IOException {
        throw new FileNotFoundException();
    }
}

  运行结果为:
在这里插入图片描述
  可以看到,在捕获到子类的异常后,父类的异常就直接跳过不再捕获了.

2 运行时异常

  调试的代码为:

package com.company;

class TestException extends Exception {
    TestException()         { super(); }
    TestException(String s) { super(s); }
}

public class Main {
    public static void main(String[] args) {
        for (String arg : args) {
            try {
                thrower(arg);
                System.out.println("Test \"" + arg +
                        "\" didn't throw an exception");
            } catch (Exception e) {
                System.out.println("Test \"" + arg +
                        "\" threw a " + e.getClass() +
                        "\n    with message: " +
                        e.getMessage());
            }
        }
    }
    static int thrower(String s) throws TestException {
        try {
            if (s.equals("divide")) {
                int i = 0;
                return i/i;
            }
            if (s.equals("null")) {
                s = null;
                return s.length();
            }
            if (s.equals("test")) {
                throw new TestException("Test message");
            }
            return 0;
        } finally {
            System.out.println("[thrower(\"" + s + "\") done]");
        }
    }
}

  运行结果很简单,这里不再给出,可自行测试.

3 小节

  异常的捕获首先会处理子类异常,如果子类异常已被捕获,那么父类异常就会跳过.如果直接捕获父类异常,则所有的子类异常都将跳过,这肯定是很粗糙的处理方式,应该避免.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值