自定义检查异常Java

时间:2015-03-20 04:35:41

标签: java exception custom-exceptions

我试图理解异常,当我尝试实现自定义的异常时,我遇到了错误。我被给出了一个指令来创建一个没有构造函数,将下面的字符串传递给超级构造函数。我一直遇到编译器错误,我不确定如何修复它们。自定义文件看起来像这样

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\Homework\1331\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

1 个答案:

答案 0 :(得分:2)

需要在方法签名中捕获或声明已检查的异常。您正在捕捉UnknownRegionException,但您看到的错误表明该代码可能会引发其他一些例外情况,例如FileNotFoundExceptionPokemonAlreadyExistsException以及PartyIsFullException。所以,那些需要被捕获在catch块中或者在方法签名中声明如下:

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

在I / O相关方法(例如对文件进行操作)中可以看到已检查异常的常见情况。扩展RuntimeException的未经检查的例外情况更为常见,并且没有必要的详细语法。

修改

即使您的代码知道您的UnknownRegionExceptionScanner也不知道它,因此无法抛出它。扫描程序仅声明它会抛出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是一个它的子类。你唯一的选择就是自己抛出异常。