Java基础中throw和throws详解

Java基础-throw和throws

虽然了解一些有关 Java 的异常处理,但是发现自己对 throw 和 throws 二者还不是很清楚,所以想深入的理解理解。

抛出异常的三种方式

系统自动抛出异常、throw 和 throws三种方式。

1、系统自动抛出异常

public class ThrowTest {
    
    public static void main(String[] args) {
        int a = 0;
        int b = 1;
        System.out.println(b / a);
    }

}

运行该程序后系统会自动抛出 ArithmeticException 算术异常。

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

2、throw
throw 指的是语句抛出异常,后面跟的是对象,如:throw new Exception,一般用于主动抛出某种特定的异常,如:

public class ThrowTest {
    
    public static void main(String[] args) {
        String string = "abc";
        if ("abc".equals(string)) {
            throw new NumberFormatException();
        } else {
            System.out.println(string);
        }
    }

}

运行后抛出指定的 NumberFormatException 异常。

Exception in thread "main" java.lang.NumberFormatException
    at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

3、throws
throws 用于方法名后,声明方法可能抛出的异常,然后交给调用其方法的程序处理,如:

public class ThrowTest {

    public static void test() throws ArithmeticException {
        int a = 0;
        int b = 1;
        System.out.println(b / a);
    }

    public static void main(String[] args) {
        try {
            test();
        } catch (ArithmeticException e) {
            // TODO: handle exception
            System.out.println("test() -- 算术异常!");
        }
    }

}

程序执行结果:

test() -- 算术异常!

throw 与 throws 比较

1、throw 出现在方法体内部,而 throws 出现方法名后。
2、throw 表示抛出了异常,执行 throw 则一定抛出了某种特定异常,而 throws 表示方法执行可能会抛出异常,但方法执行并不一定发生异常。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值