《Java 程序设计》— 异常处理

来源:互联网 发布:淘宝品牌授权是正品吗 编辑:程序博客网 时间:2024/06/02 15:58

Java异常类的父类Throwable,直接派生两个子类:Error类和Exception类。

Error 是与系统或JVM相关的异常,标志着严重的系统错误。

Exception 用于用户程序可能捕捉的异常。它有一个子类RuntimeException,该类型的异常自动为Java程序定义包括被零除和数组下标越界等这样的异常错误。RuntimeException及其子类被称为运行时异常。

      Exception类及其子类继承Throwable若干方法:

      public String getMessage() 该方法返回一个详细描述异常的字符串。

      public String toString() 该方法返回一个简洁描述该异常的字符串。

      public void printStackTrace()

 

非检查型异常:Error及其子类和RuntimeException及其子类。

      ArithmeticException、ArrayIndexOutOfBoundsException、ClassCastException、IndexOutOfBoundsException、EmptyStackException、NegativeArraySizeException、NullPointerException、NumberFormatException、StringIndexOutOfBounds

检查型异常:Exception及其除了RuntimeException以为的所有子类。

      ClassNotFoundException、CloneNotSupportedException、FileNotFoundException、IllegalAccessException、IOException、InterruptedException

 

异常的捕获与处理:

try语句:try-catch-finally,finally子句提供统一的出口。finally子句是可选的,通常可以进行资源的清除工作。

    注意:try子句后至少应该有一个catch子句或finally子句。

    说明:1、不论异常是否发生,finally块总是被执行。(当一个异常没有对应的catch时,执行完finally后,再将这个异常抛给上层)。

             2、无论有没有catch块,一旦异常出现,同一try块中异常发生点以后的代码都不被执行。

             3、当没有catch块处理异常时,默认异常处理程序打印出有关的异常信息并终止程序。

例如:

public class ExceptionCatch{public static void main(String[] strs){System.out.println("RuntimeException test: ");int a = 5;int b = 0;for(int i=1; i>=0; i--){try{System.out.println("i="+i);b=a/i;System.out.println("After no exception occur!");}/*catch(ArithmeticException e){System.out.println("Catch block, i.e.exception handling code.");}*/finally{System.out.println("Finally block!");}System.out.println("After finally block!");}}}

抛出异常:

指定方法抛出的异常:

<返回类型><方法名>(<参数列表>)throws <异常类型列表>

        <方法体>

例如:

public void readFile(String file) throws FileNotFoundException{        FileInputStream f = new FileInputStream(file);        ..........}

 throw语句抛出的异常: 

throw <throwable 或其子类对象>;

 注意:1、一般这种抛出异常的语句应该被定义为在满足一定条件时执行。(如:把throw语句放在if语句的if分支中)。

          2、catch后的参数类型必须和throw后的表达式类型一致。(即或者一样,或者前者为后者的父类)

          3、含有throw语句的方法,应该在方法头定义中增加如下部分:throws <异常类名列表>

例如:

public class TestThrow{public static void main(String args[]) throws ArrayIndexOutOfBoundsException{int a[]={1,2,3};int i = 3;if(i>2 || i<0) throw new ArrayIndexOutOfBoundsException();else System.out.println(a[i]);}}

 

 

自定义异常类:

1、声明一个新的异常类,使之以Exception类或者其他某个已经存在的系统异常类或用户异常类为父类。

2、为新的异常类定义属性和方法,或覆盖父类的属性和方法,使这些属性和方法能够体现该类所对应的错误的信息。

原创粉丝点击