您的位置:首页 > 职场人生

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

2015-08-18 21:12 656 查看
   
                                          第一部分:  异常的认识

异常体系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后面跟异常类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息