好的,所以我有一堆跨 SO 和程序员的异常相关问题,但要问的太多了,要么我不知道该输入什么,要么没有那么多人问过。
那么,假设我有一个抛出 FileNotFoundException
(FNFE) 的方法。然后我有另一个使用第一个方法的方法,但也会抛出 IOException
(IOE)。
我的处理程序会捕获两者并分别执行不同的操作,但我的 IDE (IntelliJ) 发出信号表明我“已经在抛出列表中有一个更一般的异常,‘java.io.IOException’”。
我知道这样做会奏效:
public File openOrCreate(String pathStr) throws FileNotFoundException,
IOException {
try {
// Method that generates the FNFE
Path path = ReposioryProposition.getPath(pathStr);
File file = path.toFile();
catch (FileNotFoundException fnfe) {
throw fnfe;
}
if (!file.exists())
file.createNewFile(); // IOE
return file;
}
但我需要明确地这样做吗?它会在没有显式版本的情况下工作吗?或者更危险的是,有时在没有显式版本的情况下也能工作。
为了确保我们在同一页上,我最初是这样写的:
public File openOrCreate(String pathStr) throws FileNotFoundException,
IOException {
Path path = ReposioryProposition.getPath(pathStr);
File file = path.toFile();
if (!file.exists())
file.createNewFile();
return file;
}
但我不确定会发生什么,FNFE 是被抛出还是被吞没了?我的意图是分别捕捉它们,并对一个进行不同的处理。
最佳答案
您只需在 throws
列表中包含更一般的异常。这已经指定该方法可以抛出此异常的任何子类。
特别是无论如何你都必须处理更一般的异常,而且这个异常处理器也会处理子类。如果你想显式处理子类,你必须在更一般的异常之前捕获它:
try {
...
}
catch (FileNotFoundException e) {
// handle subclass
}
catch (IOException e) {
// handle general exception (this will not be executed if the
// exception is actually a FileNotFoundException
}
关于java - 抛出主要异常和子类型,有没有正确的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32823630/