I'm currently working on a project and I've come upon a bit of a head scratcher. I've been programming in Java for about two years, and I've covered exceptions, but never properly understood them.
In my current situation I've got my main method which initializes a class
WikiGraph wiki = wiki = new WikiGraph(getFile());
The Wikigraph constructor takes a filename which I get via a DialogBox in the getFile()
method.
The constructor for wikigraph then calls a method called loadfile(filename)
which attemps to load and parse the file given.
The loadfile()
method is where I will throw an IncorrectFileTypeError.
My question is, where should I handle this?
At the moment I catch it in the loadfile()
method
try {
//load file
} catch (IncorrectFileTypeError e){
System.out.println("Incorrect file type: "+filename+": "+e.getMessage());
throw new IncorrectFileTypeError();
}
But I also catch it at the WikiGraph initialization like so:
while(wiki==null){ //While There is no valid file to add to the wikigraph
try {
wiki = new WikiGraph(getFile()); //Try to load file
} catch (IncorrectFileTypeError e) { //If file cannot be loaded
JOptionPane.showMessageDialog(null, "Incorrect File Type Given. Please Choose another file."); //Display error message
getFile(); //Prompt user for another file
}
}
Now is the way I've handled the error the correct/best way? Or should it be handled elsewhere, such as in the getFile()
method?
EDIT: I suppose I should make the file issue a bit clearer. The File extension is not what the IncorrestFileTypeError is based on, and thus it may be a misleading error name. The file given may have pretty much any extension, its the contents of that must be well formed.
In this case, I would avoid using exceptions as your primary method of dealing with incorrect file types. If an exception can regularly be triggered by user input, it really shouldn't be treated as an exception. Here's the approach I would take:
This approach gives you the best of both worlds - you have the opportunity to alert users when invalid data is provided, while still ensuring from WikiGraphs perspective that the information provided is accurate. It gives developers working against a WikiGraph a way to ensure their input is valid without necessarily requiring exception handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With