gpt4 book ai didi

java - 需要捕获 IOException 和异常

转载 作者:行者123 更新时间:2023-11-30 03:30:54 28 4
gpt4 key购买 nike

如果使用扫描仪对象读取 txt 文件的程序只产生 FileNotFoundException,那么是否应该始终捕获 IOException/Exception?

这样的额外代码是不需要的还是重要的?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class TestingScanner {
public TestingScanner() {
readFile("dummy.txt");
}

public void readFile(String filePath) {
File file = new File(filePath);
Scanner scanner = null;

try {
scanner = new Scanner(file);

while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.matches("^.+@yahoo\\.com?(\\.uk)?$"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("ERROR: Couldn't Load in " + filePath);
e.printStackTrace();
} finally {
if (scanner != null)
scanner.close();
}
}
}

最佳答案

我的经验法则是广泛使用异常捕获(捕获异常或可抛出的异常),除非有一些特定的事情我想对特定的异常做不同的事情。

例如,如果一个方法抛出两个不同的异常,并且我将处理相同的异常,那么我将只捕获异常。但如果我以不同的方式处理它们,那么我会单独捕获每个并相应地处理它们。

这种方法的关键在于“RuntimeExceptions 怎么样”。一种思想是允许运行时异常冒泡。但我发现,在我捕获异常的情况下,我想要所有异常......有时甚至是 Throwable(我因为只捕获 Exception 而不是 Throwable 而被烧伤了一次)。

以下是一些示例:

public void myMethod() throws IOException, FileNotFoundException ();

在我不想让异常出现的情况下(需要处理所有异常)

try{
myMethod();
catch(Exception e) {
//handle it
}

在我捕获异常并需要对 FileNotFound 执行不同操作的情况下。

try{
myMethod();
catch(FileNotFoundException fe){
//handle file not found
}
catch(Exception e) {
//handle it
}

在我让异常冒泡的情况下,因为我知道链的更上游有一些非常酷的异常处理代码正在处理它,并且我想避免多次记录异常:

myMethod();

在我让异常冒泡(FileNotFound 除外)的情况下。

try{
myMethod();
catch(FileNotFoundException fe){
//handle file not found
}

关于java - 需要捕获 IOException 和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29084016/

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