zoukankan      html  css  js  c++  java
  • Java 中的两种异常(Checked exceptions 和 Unchecked exceptions)

    Java中定义了两种类型的异常

    1. Checked exceptions:checked exceptions继承自Exception类,调用抛出这种异常API的客户端代码必须要处理导常,否则是不能通过编译的,该异常要么被catch子句捕获要么通过throws子句继续抛出。如:SQLException
    2. Unchecked exceptions:RuntimeException也是继承自Exception类,然而所有继承自RuntimeException的异常被特殊对待,没有要求客户端调用时必须处理这种类型异常。如:NullPointerException、ArrayIndexOutOfBoundException

    Checked exceptions

    ExceptionTester类

    package cn.sehzh;
    
    public class ExceptionTester {
    
        public void testException() throws Exception {
            throw new Exception("异常");
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Main类

    package cn.sehzh;
    
    public class Main {
        public static void main(String[] args) {
            ExceptionTester exceptionTester = new ExceptionTester();
            try {
                //客户端调用时必须捕获或抛出,这里采用捕获
                exceptionTester.testException();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Unchecked exceptions

    ExceptionTester类

    package cn.sehzh;
    
    public class ExceptionTester {
    
        public void testException(){
            throw new RuntimeException("运行时异常");
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Main类

    package cn.sehzh;
    
    public class Main {
        public static void main(String[] args) {
            ExceptionTester exceptionTester = new ExceptionTester();
            //这里没有要求客户端调用时必须处理
            exceptionTester.testException();
        }
    }
  • 相关阅读:
    剑指 Offer 06. 从尾到头打印链表
    剑指 Offer 05. 替换空格
    剑指 Offer 04. 二维数组中的查找
    14. 不修改数组找出重复的数字
    剑指 Offer 03. 数组中重复的数字
    231. 2 的幂
    1394. 完美牛棚
    10. 正则表达式匹配
    3726. 调整数组
    474. 一和零
  • 原文地址:https://www.cnblogs.com/zjj1996/p/9140254.html
Copyright © 2011-2022 走看看