[英]Should I use exceptions to produce custom errors while validating a file?
I am reading a text file, and would like to produce customized errors when the information in the file is incorrect. 我正在阅读一个文本文件,并且当文件中的信息不正确时,我想产生自定义错误。
Currently, the code to scan the file and show the contents of it in the console, is as follows: 当前,用于扫描文件并在控制台中显示文件内容的代码如下:
String importFile = "";
//I use multiple System.out.prints, just because it's less cluttered for me.
System.out.println("Please specify the directory of the file you would like to import");
System.out.println("Format should be as follows 'C:\\Users\\Example\\Example.txt'");
System.out.print("Please enter the directory: ");
importFile = keyboard.nextLine();
System.out.println("-------------------------------");
System.out.println("\tThe summary of the books in the imported catalogue is as follows");
System.out.print("===============================================================================");
System.out.format("\n|%1$-18s|%2$-25s|%3$-6s|%4$-14s|%5$-10s|","Title", "Author", "Price", "Publisher", "ISBN");
System.out.print("\n===============================================================================");
File Fileobject = new File(importFile);
try {
Scanner fileReader = new Scanner(Fileobject);
while(fileReader.hasNext()) {
String line = fileReader.nextLine();
String[] splitText = line.split("\\s-\\s");
System.out.format("\n|%1$-18s|%2$-25s|%3$-6s|%4$-14s|%5$-10s|", splitText[0], splitText[1], splitText[2], splitText[3], splitText[4]);
}
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
As seen, Title, Author, Price, Publisher & ISBN is being stored in the different spots of splitText and is being printed to the console in a neat table. 如图所示,标题,作者,价格,发布者和ISBN被存储在splitText的不同位置,并以整洁的表格打印到控制台。
Curently, the format in the file is as follows: 当前,文件中的格式如下:
String - String - Double - String - String
Some of the errors in the file may include; 文件中的某些错误可能包括:
The wrong delimiter being used (currently information is being split at each Hyphen (which is preceeded by a space, and followed by a space)) 使用了错误的定界符(当前信息在每个连字符处被分割(以空格开头,后跟一个空格))
Incorrect information (such as information missing), 信息不正确(例如信息丢失),
I want to be able to not only keep track of what spot the incorrect information is in, but also print out at the end how many errors within the file there is (and if possible only add up the valid entries which don't have any errors. As seen, i have an error for when the file isn't valid/the path entered isn't valid in there - so that's covered. 我不仅希望能够跟踪不正确信息所在的位置,而且还可以在最后打印出文件中存在多少错误(并且如果可能的话,只累加没有任何错误的有效条目)如所看到的,当文件无效/输入的路径在那里无效时,我有一个错误-涵盖了。
Any help would be appreciated. 任何帮助,将不胜感激。
Write two methods, logSuccess
and logError
for example. 写两个方法,
logSuccess
和logError
的例子。 In those two methods increment the counters. 在这两种方法中,递增计数器。 Put the counters as instance variable in the class.
将计数器作为实例变量放入类中。 Put the
println
lines in those methods too. 也将
println
行放在这些方法中。
In the end you can print the summary according to your requirements. 最后,您可以根据需要打印摘要。
And if it is your own business logic that will define whether an entry in the file is good or not then write a validate
method, that will have all the conditions defined about the validity of the entry and if all conditions are passed then call the logSuccess
otherwise call the logError
methods from the validate method. 并且如果是您自己的业务逻辑来定义文件中的某个条目是否
logSuccess
,然后编写一个validate
方法,那么它将定义有关该条目有效性的所有条件,并且如果所有条件都通过,则调用logSuccess
否则从validate方法调用logError
方法。 Call the validate method from within this loop in the existing code. 在现有代码的此循环内调用validate方法。
Since your program's intention is to handle errors gracefully, receiving an invalid input could be considered part of a normal flow of the program. 由于程序的目的是优雅地处理错误,因此可以将接收到无效输入视为程序正常流程的一部分。 On the other hand, you could also argue that invalid input is an exception from which your program knows how to recover.
另一方面,您也可能认为无效输入是程序可以从中恢复的异常。 Hence, two equally good approaches are possible.
因此,两种同样好的方法是可能的。
I would slightly prefer the second approach, which uses exceptions. 我稍微喜欢第二种方法,它使用异常。 It goes as follows: you define a
Book
object that has a static factory method for creating a Book
from String
. 它如下:定义一个
Book
对象,该对象具有一个静态工厂方法,用于从String
创建Book
。 You also define a custom exception, and declare it as part of the factory method signature: 您还定义了一个自定义异常,并将其声明为工厂方法签名的一部分:
class Book {
private Book(String title, String author, String publisher, double price, String isbn) {
...
}
public Book parse(String bookDef) throws InvalidBookException {
...
}
}
Now your main
method could loop through strings in the file, parse books, and catch InvalidBookException
exception as it goes through the file. 现在,您的
main
方法可以遍历文件中的字符串,解析书籍,并在遍历文件时捕获InvalidBookException
异常。 The exception could provide information about what's wrong with the input; 异常可以提供有关输入错误的信息。 the
main
should keep line number for providing detailed output at the end: main
应保留行号以在最后提供详细的输出:
int lineNumber = 0;
List<String> warnings = new ArrayList<>();
while(fileReader.hasNext()) {
lineNumber++;
try {
Book b = Book.parse(fileReader.nextLine());
... // Print the content of b
} catch (InvalidBookException ibe) {
String message = "Line "+lineNumber+": "+ibe.getMessage();
warnings.add(message);
}
}
if (!warnings.isEmpty()) {
... // Display warnings
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.