7.1 处理错误

来源:互联网 发布:淘宝 天猫购物券 编辑:程序博客网 时间:2024/05/22 22:14
  1. 输入会出错
  2. 设备会出错
  3. 存储会出错
  4. 代码错误

1 异常分类

这里写图片描述

运行时异常

  • 一个失败的强制类型转换
  • 数组超出异常
  • 空指针异常

其他不是运行时异常

  • 试图在文件尾部读取数据
  • 试图打开不存在的文件
  • 试图从给定字符串寻找类,而这个类不存在

一旦有运行时异常,那是我们的错,程序没写好。

错误和运行时异常属于未检查异常,其他异常成为已检查异常。


2 声明已检查异常

对于可能出现异常的部位要对异常进行检测。

public FileInputStream(String name) throws FileNotFoundException

例如,这个FileInputStream类,如果正确运行,则用name新建了一个FileInputStream对象,如果出现异常则不会创建对象而是抛出FileNotFoundException异常。

下面情况应该抛出异常:

  1. 调用一个会抛出已检查异常的方法
  2. 程序运行过程中发现错误
  3. 程序出现错误
  4. Java虚拟机和运行时库出现内部错误
class MyAnimation{    ...    //一个方法可以抛出多个可能的异常    public Image loadImage(String s) throws FileNotFoundException, EOFException    {        ...    }}

3 如何抛出异常

String readData(Scanner in) throws EOFException{    . . .    while (. . .)    {        if (!in.hasNext()) // EOF encountered        {            if (n < len)            {                String gripe = "Content-length: " + len + ", Received: " + n;                throw new EOFException(gripe);            }                       }        . . .    }    return s;}
  1. 找到合适的异常类
  2. 创建这个类的对象
  3. 抛出这个异常

注意:一旦决定抛出异常后,就不用考虑这个方法的返回值问题了,因为,方法都没有运行成功,要什么结果。


4 创建异常类

class FileFormatException extends IOException{    public FileFormatException() {}    public FileFormatException(String gripe)    {        super(gripe);    }}
String readData(BufferedReader in) throws FileFormatException{    . . .    while (. . .)    {        if (ch == -1) // EOF encountered        {            if (n < len)                throw new FileFormatException();        }        . . .    }    return s;}
0 0