Raising an exception when trying to see if a item is selected in a listbox
I am trying to raise an exception if a user clicks the delete button but doesn't select a item in the listbox.
This is what I have:
try
{
if (dataListBox.SelectedIndex == null)
throw new Exception;
//deletes selected items
dataListBox.Items.RemoveAt(dataListBox.SelectedIndex);
isDirty = true;
}
catch (Exception err)
{
//spits out the errors if there are any
Me开发者_开发百科ssageBox.Show(err.Message, "Enter something into the txtbox", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Use
SelectedIndex == -1
to know that nothing is selected.
You don't really need to throw an exception here, you could do the following:
if (dataListBox.SelectedIndex == -1)
{
MessageBox.Show(err.Message, "Enter something into the txtbox", MessageBoxButtons.OK, MessageBoxIcon.Error)
}
else
{
//deletes selected items
dataListBox.Items.RemoveAt(dataListBox.SelectedIndex);
isDirty = true;
}
You should not use exceptions to check values.
Do something like:
if (dataListBox.SelectedIndex >= 0)
{
//standard flow code
}
else
{
MessageBox.Show("Enter something into the txtbox",_
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
instead.
The test is wrong, check for -1. And it is missing the parentheses, throw new Exception().
This is however very inappropriate code in many different ways. That starts by throwing Exception instead of a specific exception derived class object. Your catch clause will catch every exception, including ones thrown by other mishaps like a bug in your code. You tell the user to enter something when she actually did.
Furthermore, exceptions should only be used for exceptional circumstances. There is nothing exceptional about the user forgetting to do something. Just display the message in the if() statement, do the rest in the else clause.
Furthermore, you should not even allow the user to fall into this trap. Only set the Delete button's Enabled property to true when you see that she's selected something.
精彩评论