An issue I've recently stumbled upon and debated is how to handle exceptions in my code. For this example, the user is adding a new category to PassShed, and I don't want a blank category to be entered. Here are the two separate methods I'm debating (in pseudocode):
Method 1
- Code: Select all
void submitButtonClickEvent()
{
if (categoryNameTextBox.Text.Length > 0)
{
AddCategory(categoryNameTextBox.Text);
}
else
{
MessageBox.Show("Blank name.");
}
}
As you can see here, an exception isn't thrown. The input is simply validated at the GUI level. As I understand it, this could be considered best practice based on the fact that invalid user input should be expected and is therefore not exceptional, i.e. it is not necessary to throw an exception.
Method 2
- Code: Select all
void AddCategory(string input)
{
if (input.Length == 0)
{
throw new ArgumentException("Blank name.");
}
}
void submitButtonClickEvent()
{
try
{
AddCategory(categoryNameTextBox.Text);
}
catch (ArgumentException argEx)
{
MessageBox.Show(argEx.Message);
}
}
With this approach, my AddCategory() method handles the exception. The benefits I see here are: 1.) the code in Method 1 would need to be duplicated if I were to enable another way for a category to be added (automatically generated templates, for example). 2.) Given the way the method is defined, wouldn't an incorrectly formatted (null) string parameter be an exceptional error worth catching?
It seems like there are a billion different answers for this, so I'm looking for your opinion on the best practice.