自定义检查异常 Java

Custom Checked Exception Java

我试图了解异常,但在尝试实施我制作的自定义异常时遇到错误。我被指示制作一个无构造函数,将下面的字符串传递给超级构造函数。我不断收到编译器错误,但我不确定如何修复它们。自定义文件如下所示

import java.io.*;

public class UnknownRegionException extends FileNotFoundException {

    public UnknownRegionException() {
        super("Could not find your region!");
    }
}

并且此代码块 运行 不正确

public Adventure(String file) {
    try {
        File inFile = new File(file);
        Scanner scan = new Scanner(inFile);
        int i = 0;
        while (scan.hasNext()) {
            String name = scan.nextLine();
            pokemon[i] = name;
            i++;
        }
    } catch (UnknownRegionException e) {
        System.err.println(e);
    }
}

我得到的错误如下

D:\Documents\Google Drive\Homework31\HW8>javac Adventure.java
Adventure.java:23: error: unreported exception FileNotFoundException; must be ca
ught or declared to be thrown
            Scanner scan = new Scanner(inFile);
                           ^
Adventure.java:63: error: unreported exception PokemonAlreadyExistsException; mu
st be caught or declared to be thrown
            throw new PokemonAlreadyExistsException(message);
            ^
Adventure.java:78: error: unreported exception PokemonAlreadyExistsException; mu
st be caught or declared to be thrown
            throw new PokemonAlreadyExistsException();
            ^
Adventure.java:84: error: unreported exception PartyIsFullException; must be cau
ght or declared to be thrown
                throw new PartyIsFullException();
                ^
Adventure.java:99: error: unreported exception FileNotFoundException; must be ca
ught or declared to be thrown
        PrintWriter outWriter = new PrintWriter(outFile);
                                ^
5 errors

需要在方法签名中捕获或声明已检查的异常。您正在捕获 UnknownRegionException,但您看到的错误表明代码可能会引发其他几个异常,例如 FileNotFoundExceptionPokemonAlreadyExistsExceptionPartyIsFullException。所以,那些要么需要在你的 catch 块中捕获,要么像这样在方法签名中声明:

public Adventure(String file) throws FileNotFoundException, PokemonAlreadyExistsException, PartyIsFullException {

检查异常常见于I/O相关方法(如操作文件)。扩展 RuntimeException 的未经检查的异常更为常见,并且没有必要的冗长语法。

编辑

即使您的代码知道您的 UnknownRegionExceptionScanner 也不知道它,因此无法抛出它。 Scanner 只声明它抛出 FileNotFoundException。如果你想让它 表现得 就好像它抛出 UnknownRegionException 你需要捕获 FileNotFoundException 并将消息包装在 UnknownRegionException

public Adventure(String file) throws UnknownRegionException {
    try {
        File inFile = new File(file);
        Scanner scan = new Scanner(inFile);
        int i = 0;
        while (scan.hasNext()) {
            String name = scan.nextLine();
            pokemon[i] = name;
            i++;
        }
    } catch (FileNotFoundException e) {
        throw new UnknownRegionException(e.getMessage());
    }
}

除此之外,Scanner 无法抛出一个异常,该异常是它声明抛出的异常的子类。本质上,FileNotFoundException 知道 IOException 因为它是 IOException 的子类,但它不知道 UnknownRegionException 因为 UnknownRegionException 是它的子类。您唯一的选择是自己抛出异常。