`

114_面向对象(多异常处理)_黑马程序员_Java基础视频

阅读更多
/*
对多异常的处理
1.生命异常时,建议声明更为具体的异常,这样处理可以更具体
2.对方声明几个异常,就应有几个catch块。
如果多个catch块中的异常出现继承关系,父类异常catch块放在最下面。
不要定义多余的catch块。
3.建议在进行catch处理时,catch中一定要定义具体的处理方式,不要
简单定义一句e.printStackTrace(),也不要简单的输出一条语句。

一般在catch块中写存储日志代码。将异常日志写到硬盘中。
*/
class Demo{
	int div(int a,int b)throws AritchmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws声明了该功能可能会出现问题
	{
		int[] arr = new int[a];
		System.out.println(arr[4]);
		return a/b;//jvm在这检测到异常,new AritchmeticException()
	}
}

/*class Test{
	public static void main(String[] args){
		Demo d = new Demo();
		int x = d.div(4,0);
		System.out.println("x="+x);
		
		System.out.println("over");
	}
}*/
class Test{
	public static void main(String[] args){
		Demo d = new Demo();
		try{
			int x = d.div(4,0);//new AritchmeticException()
			System.out.println("x="+x);
		}
		catch(AritchmeticException e){//Exception e = new AritchmeticException()
			System.out.println("分母为0了");
			System.out.println(e.getMessage());//信息异常
			System.out.println(e.toString());//异常名称:异常信息
			e.printStackTrace();//异常名称,异常信息,异常出现的位置
			//jvm默认的异常处理机制,就是在调用printStackTrace方法
		}
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println(e.toString());
			System.out.println("角标出界");
		}
		System.out.println("over");
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics