简体   繁体   中英

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.

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. In those two methods increment the counters. Put the counters as instance variable in the class. Put the println lines in those methods too.

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. Call the validate method from within this loop in the existing code.

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 . 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. 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:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM