When the user clicks save and there is nothing in the listbox, I want to raise an error.
I figured I would use a try catch block like so:
try
{
//when you go to save, and the list box is empty, you should get an error message
if (dataListBox.Items.Equals(null))
throw new Exception();
//i wanted to save on the form_close event, so i put the save data into a method and just call the method from this event
this.save();
}
catch (Exception err)
{
//spits out the errors if there are any
MessageBox.Show(err.Message, "List Box is empty", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
But this isn’t working for me. It still saves and no message box comes up.
Don’t do so at all. Compare:
With:
It makes it easier to spot the logical bug. Because we’ve separated exceptional and non-exceptional cases, we can see that we aren’t looking for the real possible exception. As is, if you had a user fill in the list properly, but the save failed because of a real exception, you are going to say “List box is empty” in your message box’s caption, which will confuse the user. This becomes plainer now, and it’s easier to fix that bug: