• throw和throws 的区别


    一、throw 和 throws 的区别

    throw 则是用来抛出一个具体的异常类型。

    throws 用来声明一个方法可能产生的所有异常,可以跟多个异常类名,用逗号隔开 表示抛出异常,由该方法的调用者来处理。
    throws表示出现异常的一种可能性,并不一定会发生这些异常。

    小结

    1.throw是语句抛出一个异常,throws是方法可能抛出异常的声明

    2.throws出现在方法函数头,而throw出现在函数体

    3.throw是指抛出一个异常的动作,而throws代表一种状态,指的是可能有异常抛出。

    4.throw只能用于抛出一种异常,而throws可以抛出多个异常。

    二、示例

    示例来源:https://zhuanlan.zhihu.com/p/448314699

    1、throw

    TestThrow.java

    public class TestThrow {
        /*
         * 定义一个检查非负数的函数
         */
        public static void checkNegativeNum(int num) {
            if (num < 0) {
                throw new ArithmeticException("不能输入负数!");
            } else {
                System.out.println("输入的数字是:" + num + ",合法!");
            }
        }
    
        public static void main(String[] args) {
            TestThrow obj = new TestThrow();
            obj.checkNegativeNum(-3);
        }
    }

    结果:

    Exception in thread "main" java.lang.ArithmeticException: 不能输入负数!
        at TestThrow.checkNegativeNum(TestThrow.java:7)
        at TestThrow.main(TestThrow.java:15)

    2、throws

    TestThrows.java

    public class TestThrows {
        public static int divideNum(int m, int n) throws ArithmeticException {
            int div = m / n;
            return div;
        }
    
        public static void main(String[] args) {
            TestThrows obj = new TestThrows();
            try {
                System.out.println(obj.divideNum(45, 0));
            } catch (ArithmeticException e) {
                System.out.println("Number cannot be divided by 0");
            }
            System.out.println("Rest of the code..");
        }
    }

    结果:

    Number cannot be divided by 0
    Rest of the code..

    3、throw和throws混合使用

    TestThrowAndThrows.java

    public class TestThrowAndThrows {
        static void method(String s) throws ArithmeticException, UnsupportedOperationException {
            System.out.println("Inside the method()");
            if (s.equals("PUT")) {
                throw new UnsupportedOperationException("This request is not supported");
            } else {
                throw new ArithmeticException("throwing ArithmeticException");
            }
        }
    
        public static void main(String[] args) {
            try {
                method("GET");
            } catch (ArithmeticException e) {
                System.out.println("caught ArithmeticException");
            } catch (UnsupportedOperationException e) {
                System.out.println("caught UnsupportedOperationException");
            }
        }
    }

    结果:

    Inside the method()
    caught ArithmeticException
  • 相关阅读:
    HGOI20191115 模拟赛 题解
    HGOI20191114 CSP模拟赛 反思
    HGOI 20191108 题解
    HGOI 20191107 题解
    HGOI 20191106 题解
    HGOI 20191105 题解
    HGOI 20191103am 题解
    HGOI 20191101am 题解
    HGOI 20191031am 题解
    新的博客!!!
  • 原文地址:https://www.cnblogs.com/Zzbj/p/16636384.html
Copyright © 2020-2023  润新知