throws和throw的区别

java中抛出异常有三种方式:

  • 系统自动抛出的异常
  • throws
  • throw
1.系统自动抛出
public class test {
    public static void main(String[] args) {
        student p1 = new student();
        System.out.println(p1.getName ().equals ("1"));
	}
}

这段代码会自动抛出空指针异常
在这里插入图片描述

2.throw
public class test {
    public static void main(String[] args) {
  		int a = 12;
        if ( a== 12){
            throw new NullPointerException ("a为12");
        }
}

直接在需要的地方使用关键字throw 抛出异常
在这里插入图片描述

3.throws
public class test {


    //因为test()方法会抛出FileNotFoundException,main方法是调用者
    //则需要使用try...catch进行捕获或者抛给JVM
    //抛出时要遵循父类声明抛出“大于”子类声明抛出的原则
    public static void main(String[] args) throws Exception {
        test();
    }
    
    public static void test() throws FileNotFoundException
    {
        //因为FileInputStream构造器会抛出FileNotFoundException
        //所以需要使用try...catch块进行处理或使用throws抛给调用者
        FileInputStream f = new FileInputStream ("a.txt");

    }
}

使用throws关键字在方法上声明这个方法可能会抛出某种类型的异常,处理的话可以丢给jvm或者由程序员自己处理.

总结

  1. throw和throws出现的位置不一样
    throw出现在函数体(方法内部),throws出现在函数头;
  2. 含义不一样
    throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象;
    3.使用方法
    两个关键字最好一起使用,也就是先声明异常,在进行抛出;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值