Exceptions in eventhandlers end program

  • Thread starter Thread starter Jan Obrestad
  • Start date Start date
J

Jan Obrestad

Hello.
I'm developing an application using CF 1.0.
I found that exceptions in eventhandlers might end the program.
Let me give a short example:

I have two forms Form1 and Form2.

Form1 has a button which shows Form2:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim a As New Form2
Try
a.ShowDialog()
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub


On Form2 I have a button that throws an exception.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Throw (New Exception("Custom Exception"))
End Sub

When I click this button the messagebox appears, but then the program
just ends.
Is there any way of preventing the program from exiting? (Other than
putting try catch in all event-handlers)
 
Thank you.
Do you know if it's possible to detect if the program is closing because
of an exception?

My idea was to do the following:


Shared Sub Main()
Dim forcedClosing As Boolean
Application.Run(New Form1)
If (forcedClosing) Then

' Clean up things before exiting.
'
End If
End Sub

Do you know if this is possible?
I tried putting a try catch around Application.Run , but since the
exception is caught earlier that didn't work.

Jan
 
Well, the built-in error dialog will come up anyway but if all you want to
do is genuinely know if it closed normally or not, I'd approach it
differently. Rather than try to catch the abnormal case, you can focus on
the normal case; if your main form closes you can log somewhere that it
closed normally. If it closes abnormally, you don't log anything. Every time
your app starts, it checks the log and if there is an entry then you know
that last time it closed OK (and clear the log and write a startup entry);
if there isn't an entry, you know that it crashed (and clear the log and
write a startup entry).

Cheers
Daniel
 
Thanks for the idea. This is what I did:

Shared Sub Main()
Dim properClosing As Boolean
Application.Run(New Form1)
If (not properClosing) Then

' Clean up things before exiting.
'
End If
End Sub

And I set properClosing to true where the users ends the program.

This way I'm able to save the users unsaved data, if the program closes
because of an exception.

Jan
 
With the code you posted, I can't see how you can ever set properClosing to
true... You might as well get rid of the condition...

Cheers
Daniel
 
This is just a simplified version of my original code.
And I made one mistake writing it.

It should be:

private shared properClosing As Boolean
Shared Sub Main()
Application.Run(New Form1)
If (not properClosing) Then

' Clean up things before exiting.
'
End If
End Sub
 
Back
Top