java异常处理 throw throws

一.什么是抛出处理异常的方式

程序自己不处理异常,而把它抛给调用者,让它去处理。

1.throw,throws关键字

throw和throws都表示抛出异常的意思,但它们有区别

a.throw和throws的区别

1.throw用于方法内部,用于抛出一个异常,throws跟在方法名后面,用于声明该函数可能会出现,即告知调用者。
2.throw抛出的是一个对象,只能写一个抛出对象,throws声明的是类,可以跟多个,用逗号隔开。
3.如果函数内部有throw抛出了编译时异常,则函数必须声明该异常。

throw和throws语法结构:

  .....函数名 throws 异常类名1,异常类名2.....{

                  。。。。。。
                  。。。。。。
                   异常语句
                  throw new 异常对象;
}


除数为0,使用抛出处理方式如下:
package testexception;

public class Testthrow {
	static int a;
	static int b=4;
	static int c;
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
      test(b,c);
	}
	public static void test(int b,int c)throws Exception{
		if(c==0){
			throw new ArithmeticException();
		}
		a=b/c;
		System.out.println(a);
	}
}
打印结果:
Exception in thread "main" java.lang.ArithmeticException
at testexception.Testthrow.test(Testthrow.java:14)
at testexception.Testthrow.main(Testthrow.java:10)

从结果看出,它打印出的是栈信息,并且抛出异常后,后面的代码不会再执行。

当我们使用抛出处理的方式来处理异常时,如果调用者所调用的函数有抛出编译时异常,那么调用者必须处理该异常,选择抛给上一级或者try-catch处理方式都可以,上面代码就是main函数再抛出去,让jvm去处理。

如果有多个异常,用throw和throws怎么处理了,上面的代码中加入空指针异常,除数不为0。
代码如下:
package testexception;

public class Testthrow {
	static int a;
	static int b=4;
	static int c=1;
	static int[] array;
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
      test(b,c,null);
	}
	public static void test(int b,int c,int[]array)throws Exception{
		if(c==0||array==null){
			throw new ArithmeticException();
		}
		a=b/c;
		System.out.println(a);
	}
}
打印结果:
Exception in thread "main" java.lang.ArithmeticException
at testexception.Testthrow.test(Testthrow.java:14)
at testexception.Testthrow.main(Testthrow.java:10)
从结果看出:还是除数为0异常,抛出异常不像try-catch处理方式,它会自动判别是什么异常,抛出异常中,我们写的是什么异常,代码就会抛出什么异常。

处理如下:
package testexception;

public class Testthrow {
	static int a;
	static int b=4;
	static int c=1;
	static int[] array;
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
      test(b,c,null);
	}
	public static void test(int b,int c,int[]array)throws Exception{
		if(c==0){
			throw new ArithmeticException();
		}
		if(array==null){
			throw new NullPointerException();
		}
		a=b/c;
		System.out.println(a);
	}
}
打印结果如下:Exception in thread "main" java.lang.NullPointerException
at testexception.Testthrow.test(Testthrow.java:17)
at testexception.Testthrow.main(Testthrow.java:10)







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值