java异常捕获

java异常捕获
一、代码实例,从代码看异常捕获(无捕获到catch异常,会继续往上抛)
package cn.hbut.test1;

public final class A {

	public static void main(String[] args) {
	
		try{
			int a=1/0;
			int b[] = new int [2];
			System.out.println("开始执行赋值操作...");
			b[5]=10;
		}
		//即便有catch捕获,可与NullPointerException不符合
		catch(NullPointerException e){
			System.out.println("NullPointerException---"+e);
		}
		//数组交表越界异常
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("ArrayIndexOutOfBoundsException---"+e);
		}
	}
}

上面的异常类型有两个:
1.int  a=1/0;     会发生算术运算异常
2.b[5]=10;        由于初始化数组的大小为2,给下角标为5的数组赋值,会发生数组角标越界异常


运行结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at cn.hbut.test1.A.main(A.java:8)



分析异常:
       1.第一个catch捕获的是NullPointerException(空指针异常),由于上面程序发生的第一个异常是  int a=1/0;
是一个算术异常,无法被该异常捕获处理,所以异常继续往上抛;第二个ArrayIndexOutOfBoundsException能否处理该算术异常呢?答案是否定的,异常会继续抛送给main方法,而main方法直接抛给java虚拟机了,java虚拟机无法处理该异常,程序直接中断了,抛出Exception in thread "main" java.lang.ArithmeticException: / by zero,
后面的程序System.out.println("开始执行赋值...");无法执行了;


二、代码实例2,从代码看异常捕获(有捕获到的异常,会处理)
package cn.hbut.test1;

public final class A {

	public static void main(String[] args) {
	
		try{
			int a=1/0;
			int b[] = new int [2];
			System.out.println("开始执行赋值...");
			b[5]=10;
		}
		catch(ArithmeticException e){
			System.out.println("ArithmeticException---"+e);
		}
		//数组交表越界异常
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("ArrayIndexOutOfBoundsException---"+e);
		}
	}
}

运行结果:
ArithmeticException---java.lang.ArithmeticException: / by zero


分析异常:
 int a=1/0;异常被ArithmeticException捕获处理了,不过该处理仅仅是打印了一些异常信息,程序继续执行是否catch里面继续执行的,所以System.out.println("开始执行赋值...");该句无法执行


三、代码实例2,从代码看异常捕获(子异常在父异常之后是无法通过编译的)
package cn.hbut.test1;

public final class A {

	public static void main(String[] args) {
	
		try{
			int a=1/0;
			int b[] = new int [2];
			System.out.println("开始执行赋值...");
			b[5]=10;
		}
		//后面的数组角标越界异常无法执行,因为父异常在前,已经执行,子异常无法通过编译
		catch(Exception e){
			System.out.println("ArithmeticException---"+e);
			int b[] = new int [2];
			System.out.println("开始执行赋值...");
			b[5]=10;
		}
		//数组交表越界异常
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("ArrayIndexOutOfBoundsException---"+e);
		}
	}
}

分析:该代码无法通过编译器编译的,因为ArrayIndexOutOfBoundsException异常是Exception的子异常,在父异常之后的子异常是无法达的,所以编译器无法通过编译,更不用说运行了

分析异常:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值