Hey guys,
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.