Question

From a best practices perspective, should try / catch statements be used when implementing an object's method(s), or is it OK to code them into the methods themselves?

For example, I'm going to code a database class in C#. When I call my runCommand() method, is it considered best practice to do something like this?

 //inside class method 'runCommand()'
 try
 {
     _command = new MySqlCommand(query, _connection);
     return _command;
 }
 catch (MySqlException e)
 {
     System.Windows.Forms.MessageBox.Show(e.ToString());
     return _command;
 }

... or something like this?

//inside a Windows form and assuming an object 'myDB'
private void btnRunCommand_Click(object sender, EventArgs e) {

    try {
        myDB.runCommand("SELECT * FROM test");
    }
    catch (MySqlException e) {
        MessageBox.Show(e.ToString());
    }
Was it helpful?

Solution

It depends on the goals of your exception handling.

If the goal is to display an error message when there's an error, as in your example, the exception handling belongs in the view (the Windows form). This is helpful when user interaction is required to resolve the issue.

However, if your data model should return some default value, or attempt to recover from the exception by loading new data from a remote server, for example, this logic does not belong in the view.

OTHER TIPS

Data access code should generally not interact directly with the user. In the event that user interaction may be required within a data-access method, the caller should supply one or more delegates which can be used to request such interaction. In that way, user-interface code which calls the data access code can define methods to perform user interaction in a way consistent with the rest of the UI, and pass such methods to the data-access code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top