Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to handle an Exception

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.

like image 967
Chris Salij Avatar asked Feb 09 '10 19:02

Chris Salij


1 Answers

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:

  1. Check the file type and alert the user if the file type is invalid, through standard control flow. You might consider a static method on WikiGraph like IsFileValid(filename)
  2. In the WikiGraph initialization, throw an exception if the file type is invalid.

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.

like image 186
Ryan Brunner Avatar answered Sep 23 '22 15:09

Ryan Brunner