为什么我的try-catch在我的代码中不起作用?

huangapple go评论73阅读模式
英文:

Why is my try-catch not working in my code?

问题

我正在尝试创建一个搜索给定名称在列表中的代码。之后,它应该打印 "found" 或 "not found"。如果用户输入了不正确的文件,代码应该打印 "Reading the file " + file + " failed."。然而,即使找到了名称,它也会打印错误消息。我猜这可能是语法错误,但我花了45分钟尝试找到它。以下是我的代码:

import java.nio.file.Paths;
import java.util.Scanner;

public class IsItInTheFile {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Name of the file:");
        String file = scanner.nextLine();

        System.out.println("Search for:");
        String searchedFor = scanner.nextLine();
        boolean value=false;
        
        try(Scanner fhandle=new Scanner(Paths.get(file))){
            while(fhandle.hasNextLine()){
             
                String line = fhandle.nextLine();
                while(!(line.isEmpty())){
                    
                    String[] words=line.split(" ");
                    for(String word:words){
                        if (word.equals(searchedFor)){
                            
                            value=true;
                            
                        
                        }
                        
                    }
                    line=fhandle.nextLine(); 
                }
               
            }
            
        }catch(Exception e){
            System.out.println("Reading the file " + file + " failed.");
            
        }
        if(value){
            System.out.println("Found!");
        }else{
            System.out.println("Not found.");
        }

    }
}
英文:

I'm trying to create a code that searches for a given name on the list. Afterwards, it should print "found" or "not found". If the user enters an incorrect file, the code should print, "Reading the file " + file + " failed.". However, it prints the error message, even when the name IS found. I'm guessing its a syntax error, but I spent 45 minutes trying to find it. Here is my code:

import java.nio.file.Paths;
import java.util.Scanner;
public class IsItInTheFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Name of the file:");
String file = scanner.nextLine();
System.out.println("Search for:");
String searchedFor = scanner.nextLine();
boolean value=false;
try(Scanner fhandle=new Scanner(Paths.get(file))){
while(fhandle.hasNextLine()){
String line = fhandle.nextLine();
while(!(line.isEmpty())){
//System.out.println("Current line is "+line);
String[] words=line.split(" ");
for(String word:words){
if (word.equals(searchedFor)){
value=true;
//System.out.println(word);
}
}
line=fhandle.nextLine(); 
}
}
}catch(Exception e){
System.out.println("Reading the file " + file + " failed.");
}
if(value){
System.out.println("Found!");
}else{
System.out.println("Not found.");
}
}
}

答案1

得分: 1

问题出在内部的 while 循环中。你正在从文件中读取行,但没有检查是否还有更多行可读取。当你到达文件末尾时,它会抛出一个异常。

重构你的代码,使之只有一个 while 循环,并在其中只调用一次 fhandle.nextLine()

while (fhandle.hasNextLine()) {
    String line = fhandle.nextLine();
    if (!line.isEmpty()) {
        String[] words = line.split(" ");
        for (String word : words) {
            if (word.equals(searchedFor)) {
                value = true;
                break;
            }
        }
    }
}

为了防止将来发生这种情况,记住在 catch 子句中始终使用最具体的异常类型,例如在这里使用 catch (IOException e)。此外,当捕获异常时,你应该始终记录它,而不仅仅假设你知道它是什么以及为什么抛出的。

英文:

The problem is in the inner while-loop. You are reading lines from the file, without checking if there are more lines to read. When you get to the end of the file, it will throw an exception.

Restructure your code so that there is only one while-loop, and call fhandle.nextLine() only once within it.

        while (fhandle.hasNextLine()) {
String line = fhandle.nextLine();
if (!line.isEmpty()) {
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(searchedFor)) {
value = true;
break;
}
}
}
}

To prevent this from happening in the future, remember to always use the most specific exception type in the catch clause, for example catch (IOException e) here. Also, when you catch an exception, you should always log it some how, and not just assume you know what it was and why it was thrown.

huangapple
  • 本文由 发表于 2020年8月8日 19:43:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63314991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定