开发者

Raising an exception when trying to see if a item is selected in a listbox

开发者 https://www.devze.com 2023-01-20 03:09 出处:网络
I am trying to raise an exception if a user clicks the delete button but doesn\'t select a item in the 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消