gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:09 26 4
gpt4 key购买 nike

我有两个抛出相同异常的方法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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com