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

   

                                          第一部分:  异常的认识

异常体系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{

public static void 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{

public static void 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后面跟异常类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值