跳至主要內容

Java异常

向往大约 1 分钟java

异常结构及分类

类继承关系如下图所示:

image-20230211162330883

异常主要分为以下三种类型:

  • 检查时异常,由Java编译器检查
  • 未检查异常,也叫运行时异常,未检查的异常是Java编译器不需要开发人员处理的异常。
  • 错误,严重且通常且不可恢复

异常处理

throws

throws用于向外抛出异常,示例如下:

public int getPlayerScore(String playerFile)
  throws FileNotFoundException {
 
    Scanner contents = new Scanner(new File(playerFile));
    return Integer.parseInt(contents.nextLine());
}

try-catch

如果想尝试自己处理异常,可以使用try-catch块。可以通过重新抛出异常来处理它。

public int getPlayerScore(String playerFile) {
    try {
        Scanner contents = new Scanner(new File(playerFile));
        return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException noFile) {
        throw new IllegalArgumentException("File not found");
    }
}

finally

有些时候,无论是否发生异常,我们都需要执行代码,这时就需要使用finally关键字。示例如下:

public int getPlayerScore(String playerFile)
  throws FileNotFoundException {
    Scanner contents = null;
    try {
        contents = new Scanner(new File(playerFile));
        return Integer.parseInt(contents.nextLine());
    } finally {
        if (contents != null) {
            contents.close();
        }
    }
}

try-with-resources

当在try声明中放置继承AutoClosable引用时,不需要自己关闭资源。示例如下:

public int getPlayerScore(String playerFile) {
    try (Scanner contents = new Scanner(new File(playerFile))) {
      return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException e ) {
      logger.warn("File not found, resetting score.");
      return 0;
    }
}