黑马程序员----异常处理机制的概括

来源:互联网 发布:js格式化代码插件 编辑:程序博客网 时间:2024/05/22 14:13
   

                                          第一部分:  异常的认识

异常体系Throwable:

(1)Error:通常出现重大问题如:运行的类不存在或者内存溢出

    不编写针对代码对其处理

(2)Exception

    在运行时候出现的错误、

    Exception都是以父类名作为后缀的

    可编写针对性代码对其进行处理

 

                                         第二部分:异常的处理

Java提供了特有的语句进行处理:

try

{

     需要被检测的代码块

}

catch(异常类 变量)

{

     处理方式

}

finally

{

}

 

                                   第三部分:代码举例

(1)通过try-catch方式处理的代码举例

class Demo{

    int div(int a,int b)

    {

    return(a/b);

     }

}

 

class exception{

publicstaticvoid main(String[] args){

    Demo d=new Demo();

   try{

   int x = d.div(3, 1);//new AritchmeticException()

    System.out.println("x="+x);

    }

   catch (Exception e)//Exception e =new AritchmeticException()

    {

    System.out.println("除零了") ;

    System.out.println(e.getMessage());//BY ZERO

    System.out.println(e.toString());//异常名称:异常信息

    e.printStackTrace();//异常名称 异常信息 异常位置

    }

    System.out.println("over");// 此语句运行,如果没有try catch不会执行

  }

}

 

(2)通过throws方法代码举例

class Demo{

    int div(int a,int b)throws Exception// 通过throws申明该功能可能出现问题

     {

        return(a/b);

     }

}

 

class exception{

publicstaticvoid main(String[] args){

     Demo d=new Demo();

    try{

    int x = d.div(3, 1);//new AritchmeticException()

     System.out.println("x="+x);

     }

    catch (Exception e)//Exception e =new AritchmeticException()

     {

     System.out.println("除零了") ;

     System.out.println(e.getMessage());//BY ZERO

     System.out.println(e.toString());//异常名称:异常信息

     e.printStackTrace();//异常名称 异常信息 异常位置

      }

     System.out.println("over");// 此语句运行,如果没有try catch不会执行

   }

}

 

                            第四部分:自定义异常机制中throws与throw的区别

(1)throws用在函数上,throw用在函数内

(2)throws后面跟的异常类,可以跟多个,用逗号隔开 throw后面跟异常类

0 0
原创粉丝点击