java - 具有不同错误消息的相同异常类型

标签 java exception exception-handling

我有两个抛出相同异常的方法throws IOException

问题是每个方法都出于不同的原因抛出它,我包装了这些方法 主要是try catch,推荐的解决方法是什么? 对于相同类型的每个异常,我需要不同的消息..

public static void main(String[] args) {

try{

….


readFile(path);

convert(file)

} catch (IOException e) {
    …..
}


private static String readFile(String path) throws IOException {
    //Here files requires IOException -  Reason here cannot Read file
    String lineSeparator = System.getProperty("line.separator");
    List<String> lines = Files.readAllLines(Paths.get(path));
} 


private static String convert(String file) throws IOException {
   //Here reader requires also ioException- Reason here cannot parse file
    ObjectMapper reader = new ObjectMapper(new YAMLFactory());
    Object obj = reader.readValue(file, Object.class);

}

最佳答案

您可以通过多种方式来解决这个问题。一种方法,可能是您需要编写的新代码最繁重的方法,是从每个帮助程序方法中抛出自定义异常。然后您可以在单独的 block 中捕获每个特定的异常。

但我在这里可能建议的是,您只需将对辅助方法的两个调用分别包装在单独的 try-catch block 中:

try {
    readFile(path);
} catch (IOException e) {
    // handle first exception here
}

// more code
try {
    convert(file)
} catch (IOException e) {
    // handle second exception here
}

这是相当干净的,不需要大量的重构。如果您一直遇到这个问题,那么可以考虑为您的应用程序创建自定义异常。如果您查看许多 Java 库,您会发现它们经常使用自己的自定义异常。

如果您想走使用自定义异常的路线,您可以定义一个,例如

public class FileReadIOException extends Exception {
    public FileReadIOException(String message) {
        super(message);
    }
}

然后使用它:

private static String readFile(String path) throws FileReadIOException {
    try {
        String lineSeparator = System.getProperty("line.separator");
        List<String> lines = Files.readAllLines(Paths.get(path));
    }
    catch (Exception e) {
        throw new FileReadIOException(e.getMessage());
   }
}

try {
    readFile(path);
    // more code
    convert(file)
} catch (FileReadIOException e) {
    // handle first exception here
} catch (SomeOtherException e) {
    // handle second exception here
}

上面显示自定义异常的代码有点做作,因为实际情况是您的所有代码都抛出 IOException。在您的案例中创建自定义异常不会增加太多值(value),因为它们已经(正确地)抛出 IOException。我不确定只处理一种异常是否有意义。更典型的情况是,如果您正在处理大型企业应用程序,您会使用自定义异常来处理您自己的自定义代码出错的情况。

关于java - 具有不同错误消息的相同异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45921034/

相关文章:

java - 无法从 jar 中给出的扩展 Activity 启动 Activity

java - 将数据动态添加到 LineChart JavaFX

java - 抛出带有消息的简单异常

java - 奇怪的异常传播到主线程

android - Gradle 异常 : "There must be one branch ID(.bid) file in the root dir of the project"

iphone - objective-c 中的错误处理与异常处理

java - 具有本地内部类的 JUnit 4 测试方法在测试用例之间不一致

java - 无法使 GWT-RPC 正常工作

java - 在 java 中出现异常后继续的更好方法

powershell - PowerShell:我可以捕获所有异常的单点