Java异常    

 

 

什么是异常?

  异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。

异常发生的原因有很多,通常包含以下几大类:

  用户输入了非法数据。

    要打开的文件不存在。

    网络通信时连接中断,或者JVM内存溢出。

异常处理:

Java异常_Java异常

  Java标准库内建了一些通用的异常,这些类以Throwable为顶层父类。Throwable又派生出Error类和Exception类。

  Java的异常处理是通过5个关键字来实现的:try、catch、 finally、throw、throws。

 Java异常的分类和类结构图:

Java异常_Java异常_02

异常类型 说    明

Exception 

异常层次结构的父类

ArithmeticException

算术错误情形,如以零作除数

ArrayIndexOutOfBoundsException

数组下标越界

NullPointerException

尝试访问 null 对象成员

ClassNotFoundException

不能加载所需的类

IllegalArgumentException

方法接收到非法参数

ClassCastException

对象强制类型转换出错

NumberFormatException

数字格式转换异常,如把"abc"转换成数字

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捕获异常

  try:执行可能产生异常的代码。

  catch:捕获异常。

  finally:无论是否发生异常,代码总能执行。

public void method(){try {      // 代码段 1      // 产生异常的代码段 2      // 代码段 3} catch (异常类型 ex) {      // 对异常进行处理的代码段4}// 代码段5}

异常的处理示例:

import java.util.Scanner;/**
 * 使用try-catch-finally进行异常处理。*/public class Test {    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("请输入被除数:");        try {            int num1 = in.nextInt();
            System.out.print("请输入除数:");            int num2 = in.nextInt();
            System.out.println(String.format("%d / %d = %d",
                    num1, num2, num1/ num2));
        } catch (Exception e) {
            System.err.println("出现错误:被除数和除数必须是整数," +
                    "除数不能为零。");
            System.out.println(e.getMessage());            //System.exit(1); // finally语句块不执行的唯一情况
        } finally {
            System.out.println("感谢使用本程序!");
        }
    }
}

多重异常示例:

import java.util.Scanner;import java.util.InputMismatchException;/**
 * 多重catch块。*/public class Test {  public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      System.out.print("请输入被除数:");          try {          int num1 = in.nextInt();
          System.out.print("请输入除数:");          int num2 = in.nextInt();
          System.out.println(String.format("%d / %d = %d", 
                  num1, num2, num1/ num2));
      } catch (InputMismatchException e) {
          System.err.println("被除数和除数必须是整数。");
      } catch (ArithmeticException e) {
          System.err.println("除数不能为零。");
      } catch (Exception e) {
          System.err.println("其他未知异常。");
      } finally {
          System.out.println("感谢使用本程序!");
      }
   }
}

多重异常的执行规则:

  排列catch 语句的顺序:先子类后父类

  发生异常时按顺序逐个匹配

  只执行第一个与异常类型匹配的catch语句

 

 声明异常

 throws:声明方法可能要抛出的各种异常。

 如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。

 

抛出异常

 throw:手动抛出异常。示例如下:

 1 public class Person { 2     private String name = "";   // 姓名 3     private int age = 0;   // 年龄 4     private String sex = "男";  // 性别 5     public void setSex(String sex) throws Exception { 6         if ("男".equals(sex) || "女".equals(sex)) 7             this.sex = sex; 8         else { 9             throw new Exception(“性别必须是\"男\"或者\"女\"!");10         }11     }12 }