基础卷_异常篇 第3集 对多异常的处理

来源:互联网 发布:知画生孩子摔倒的视频 编辑:程序博客网 时间:2024/06/10 18:14
/**
*
* 1.声明异常时,建议声明更为具体的异常,这样处理的可以更具体。
* 2,对方声明几个异常,就对应有几个catch块,多余catch块的不要定义
* 如果多个catch块中的异常出现继承关系,父类异常catch一定一定要放在最下面
* 要不然,你之后写的catch块都是多余的,没什么用。
*
*
* 注意:建议在进行catch处理时,catch块中一定要定义具体的处理方式。
* 不要简单定义一句 e.printStackTrace(),
* 也不要简单的就写一条输出语句。

*/


class Demo2{//在功能上通过throws的关键字声明了该功能可能会出现问题。//有可能发生不止一个问题,以下这种声明方式其实并不好,声明更为具体的异常int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException{ //人造异常一int[] arr=new int[a];System.out.println(arr[4]);//人造异常二return a/b;}}public class Demo4_2 {public static void main(String[] args) throws Exception {Demo2 d=new Demo2();try{int x=d.div(4,0);System.out.println("x="+x);}//预先给人造异常二基本处理catch(ArithmeticException e){System.out.println(e.toString());System.out.println("被0除了!!");}//预先给人造异常一基本处理catch(ArrayIndexOutOfBoundsException e){System.out.println(e.toString());System.out.println("角标越界了!!");}catch(Exception e){System.out.println("haha"+e.toString());}System.out.println("over");}}

运行结果:


0 0