In my load event on a form, I call some method in a try catch block. When an Exception occurs, I show the user a message and after that I want to close the form. It looks like this (code in Load event):
try
{
Metehod();
}
catch(DatabaseException ex)
{
MessageBox.show("db error! " + ex.Message);
this.Close();
}
catch(Exception ex)
{
MessageBox.Show("Unknown error!" + ex.Message);
this.Close();
}
But, when this.CLose() is called, it doesn’t close the form, no, the code keeps running till the end of the load event!
Why is this? Is this logical behaviour?
Yes, it is logical behaviour. Calling Close() does not return control to the caller. The method will continue execution unless you tell it otherwise. Putting a
returnafter eachthis.Close()does the trick.