Catching exceptions within your code make a huge difference in how your program will be perceived from a user. If you do not catch the exception then in many cases your program will crash and be required to close and then reopened. However, if you catch exceptions you can handle them gracefully. You gracefully recover from an exception by notifying the user that an error has occurred, provide them details so they can contact technical support easily, reset or restart any code related properties or methods and then let the system continue to function as expected.
You can achieve this be placing you code within a try…catch block like below:
[sourcecode language="csharp" padlinenumbers="true" gutter="true"] try { List<string> fields = new List<string>(BuildFieldList(QueryString)); datagrid1.ItemsSource = BuildDataGridResult(fields, QueryResults, false).DefaultView; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Message", MessageBoxButton.OK, MessageBoxImage.Error); } [/sourcecode]
If either the BuildFieldList() method or the BuildDataGridResult() method fail then the user will receive a MessageBox showing them what the error was. They could write this down and share it with technical support so the problem could be resolved. Even if the BuildDataGridMethod() method calls other methods which fail, you will still be able to recover gracefully. However, in some cases you would not get the best messages from the error unless you handle it specifically.
It is also possible that you throw exceptions yourself from within the code, like below:
[sourcecode language="csharp"] string cannotBeEmpty = textBox1.Text; try { if (cannotBeEmpty.Length == 0) throw new ValueUnavailableException("You must enter something!"); List<string> fields = new List<string>(BuildFieldList(QueryString)); } catch (ValueUnavailableException veu) { MessageBox.Show(vue.Message, "ValueUnavailableException Message", MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Message", MessageBoxButton.OK, MessageBoxImage.Error); } [/sourcecode]
In this case if nothing has been entered into the textBox then I throw the ValueUnavailableException from within a try…catch block. Within my catch I specifically handle the ValueUnavailableException so I am certain the user receives the message I created when I threw the exception. It is possible to have multiple catch blocks for a single try. In the above example, had I not included the catch for a general Exception and the BuildFieldList() method failed the system would have crashed.