简体   繁体   English

验证文件时,我应该使用异常来产生自定义错误吗?

[英]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. 写两个方法, logSuccesslogError的例子。 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.

相关问题 在我的特定情况下,我是否应该使用自定义异常? - In my particular situation should I use custom exceptions or not? Java - 如何从 xml 验证文件中捕获所有异常/错误 - Java - How to catch all exceptions/errors from xml validating file 在Java中读取属性文件时,我应该使用try-catch还是引发自定义异常,或者两者都使用? - Should I use try-catch or throws custom exception or both while reading property file in Java? 在这种情况下我应该使用例外吗? - Should I use exceptions in cases like this? 我应该使用图像的什么值来产生哈尔小波? - what values of an image should I use to produce a haar wavelet? 我应该如何处理自定义 Hamcrest 匹配器中的异常? - How should I handle exceptions in custom Hamcrest matchers? 我应该使用一会儿(true) - Should i use a while(true) 我应该如何使用事务来防止内存不足异常? - how should i use transactions to prevent out of memory exceptions? 应该使用异常来描述用户输入错误吗? - Should exceptions be used to describe user input errors? Micronaut应该为依赖注入错误生成编译器警告/错误吗? - Should Micronaut Produce Compiler Warnings / Errors for Dependency Injection Errors?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM