异常解析

来源:互联网 发布:广州房地产交易数据 编辑:程序博客网 时间:2024/05/22 08:07

异常:程序在运行时出现的不正常情况

异常的由来:程序在运行时出现的不正常情况也被看成了对象,提取属性和行为进行描述( 比如异常信息,异常名称,异常发生的位置),从而形成了各种异常类

Throwable是Error和Exception的父类
Throwable
—Error :运行时出现的严重问题,不用写相关的处理代码
—Exception :不严重的问题,通常需要进行处理

下面一个简单的数组越界异常

class Demo7 {    public static void main(String[] args)     {        int[] arr = new int[3];        /*        当发生下标越界异常时,因为这种下标越界异常在java内部已经定义好了,所以系统会自动创建        该异常类对象,因为main函数处理不了这种异常抛给了JVM,JVM默认的处理方式就是调用该异常类对象        的printStackTrace()方法,打印出异常类名称,异常信息,异常发生的位置,然后程序中断        */        System.out.println(arr[3]); //throw new ArrayIndexOutOfBoundsException()---JVM        System.out.println("over");    }}



使用throws声明可能发生异常,那么调用者必须处理,
处理方式有两种
1:使用try{}catch(异常类 e){}处理
2:继续使用throws声明可能发生异常

class MyMath{    public int div(int a,int b)    {        return a/b; //throw new ArithmeticException()    }}class Demo9 {    public static void main(String[] args)     {        MyMath myMath = new MyMath();        try        {            int result = myMath.div(3,0); //new ArithmeticException()            System.out.println("result="+result);        }        catch(Exception e)//Exception e = new ArithmeticException()        {            //System.out.println("除数为0了");            //System.out.println(e.getMessage());//异常信息            //System.out.println(e.toString());//异常名称:异常信息            e.printStackTrace();//异常名称:异常信息  异常发生的位置        }        System.out.println("go on");    }}


class MyMath{    public int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException    {        int[] arr = new int[4];        System.out.println(arr[4]);// throw new ArrayIndexOutOfBoundsException();//如果这里抛异常了那么下面就不运行了        return a/b;//在上面不抛异常的情况下,若b为0那么抛异常    }}class Demo11 {    public static void main(String[] args)//多重异常--子类异常要写在父类异常的上边儿    {        MyMath myMath = new MyMath();        try        {            int result = myMath.div(3,0); //new ArrayIndexOutOfBoundsException()            System.out.println("result="+result);        }        catch (ArithmeticException e)//Exception e= new ArrayIndexOutOfBoundsException();        {            System.out.println("除数为0了");        }        catch(ArrayIndexOutOfBoundsException e)        {            System.out.println("下标越界了");        }    }}
0 0