My application exits after handling an ApplicationException

T

Tad Marshall

Hi,

I'm having limited luck getting an ApplicationException to work right in my
code. This is VB.NET, VS 2003, Windows XP SP2, .NET Framework 1.1.

I thought it would be convenient to take advantage of exception handling to
deal with the case of the user clicking the Cancel button while a long
operation was running. So, I declared a class inherited from
ApplicationException and I Throw one of these with the text "User pressed
Cancel" in the OnClick handler for the Cancel button. I have a
Try/Catch/Finally/End Try block around the code that is running, and it all
works great. I catch the exception, log a message that the user pressed
cancel, then run the Finally block and close all my files, and I return to
the OnClick handler for the Start button that began the operation, and it
re-enables the Start button and returns from the OnClick handler.

Then my program exits, with error code 0.

If I take out the Try stuff, VS 2003 catches it and puts up a dialog saying
that a UserInterruptException has occured with additional information "User
pressed Cancel". I can Break into the debugger and look around, but if I
Continue then it is the same as when I had the Try block ... everything
gracefully cleans up just as designed, and then the program exits, which is
NOT my design.

Am I missing something? I've used Structured Exception Handling in Win32,
and all I had to do was handle the error and my code would keep running. I
thought that was the whole point! You can exit if you want to, but if you
can handle the error and continue, then you do that instead.

Any suggestions? Thanks!

Tad
 
A

Adam Goossens

Hi Tad,

Wow, that must be irritating. Did you start the application message loop
by passing an instance of your form to Application.Run()? If you did and
you close the form, the application will terminate.

As long as you've caught the exception, you shouldn't have a problem.
The only thing I can think of is that there's some form of code there
doing something it shouldn't be. A logic error, perhaps?

Let me know how you go...this has me intrigued :)
Regards,
-Adam.
 
C

Cor Ligthert

Tad,

Can you show some code from that catch .... finally block
(copied first in a notebook, and than from that in the message, direct it is
mostly unreadable)

Cor
 
T

Tad Marshall

For the moment, I did the less elegant thing of setting a flag when Cancel
is clicked and testing for it in my loop. But I left the Try/Catch/Finally
code in place.

So what next surprised me was when I messed up a SQL statement and got an
exception from ADO.NET. My code caught the exception, closed its files, and
returned to its message loop, no problem, no early exit.

Yes, right now the code starts running in Module MainModule in a Sub Main,
and it creates the form and runs it. Here's that bit of code:

Public Sub Main()

' Enable XP visual styles
'
Application.EnableVisualStyles()
Application.DoEvents()

' Create and run our form
'
f = New Form1
Application.Run(f)

End Sub

I'll post the code for the exception declaration, the Throw and the
Try/Catch/Finally in my next message ...

Tad
 
T

Tad Marshall

Sure, here's some code. In my earlier reply I mentioned that I saw the
exception handling working fine (no early exit) when it was given a real
(not self-generated) exception, so I'm not sure what's going on. It is as
if the main message pump noticed that an ApplicationException had occurred
and set a flag telling itself to exit once all user code had been returned
from. I call DoEvents() after I put things in a Listbox so that the user
can see them, so various message loops are being allowed to run ...

Here's my declaration for my exception:

' When the user clicks the Cancel button while a walk is in progress, we
throw
' this exception to break out in an orderly way
'
Public Class UserInterruptException
Inherits ApplicationException

Public Sub New()
MyBase.New()
End Sub

Public Sub New(ByVal exceptionText As String)
MyBase.New(exceptionText)
End Sub

Public Sub New(ByVal exceptionText As String, ByVal inner As Exception)
MyBase.New(exceptionText, inner)
End Sub

Here's where I throw the exception:

Private Sub Close_Cancel_button_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Close_Cancel_button.Click

' The Cancel button interrupts a walk, the Close button exits the
program
'
If inProgress Then
Throw New UserInterruptException("Cancel button pressed.")
Else
End
End If

End Sub

Here's the Try/Catch/Finally block (slightly edited since it is very long):

' Run everything inside an exception handler so that files get
closed properly
' whether the user clicks Cancel or something else happens
'
Try

' Open all of our output files, write headers into the .csv
files
'
createOutputFiles()

' Initialize the variables we'll need for this procedure
'
initializeVariables()

' Create our SQL Connection
'
f.AddTimestampedRecord("Opening Stocks database")
StockDB = New SqlConnection("Data Source=localhost;" & _
"Integrated Security=SSPI;Initial Catalog=Stocks")

' Build SQL text to pull in the data we want
'
cmd = StockDB.CreateCommand()

cmd.CommandText = "SELECT " & _
<huge select statement trimmed to save space>
"ORDER BY TradeDate, PERMNO"

' Open the table
'
f.AddTimestampedRecord("Sending SQL command: """ &
cmd.CommandText & """")
StockDB.Open()

' Run the data reader
'
f.AddTimestampedRecord("Executing the reader")
reader = cmd.ExecuteReader

' Read from the reader until data is exhausted
'
haveData = reader.Read()
Do While (haveData AndAlso Not f.cancelPressed)

' Handle the next row of the table
'
Dim retval As Integer = reader.GetValues(objArray)

' Try to match dates
'
newDate = CType(objArray(1), DateTime)
If recordsRead = 0 Then
dt = newDate
End If
If newDate = dt Then
If tdc(t) > twoDays.GetUpperBound(1) Then
Throw New ApplicationException("Table overflow.")
Else
twoDays(t, tdc(t)).PERMNO = CType(objArray(0),
Integer)
<more stuff cut out to save space>
tdc(t) += 1
End If

' Read the next row of data for the next pass
'
recordsRead += 1
haveData = reader.Read()

Else

' Process the data we just read
'
processOneDay()

End If

Loop

Catch ex As UserInterruptException

f.cancelPressed = True

Catch ex As Exception

f.AddTimestampedRecord("Exception: " & ex.Message)

Finally

' Note if Cancel was pressed, then clear the flag
'
If f.cancelPressed Then
f.AddTimestampedRecord("Process interrupted by user")

' The docs say that we can speed things up by canceling the
' command ... seems to be true
'
cmd.Cancel()
End If
f.cancelPressed = False

' Close the reader and the database
'
f.AddTimestampedRecord("Closing the reader")
If Not reader Is Nothing Then
reader.Close()
End If
reader = Nothing

f.AddTimestampedRecord("Closing the database")
If Not StockDB Is Nothing Then
StockDB.Close()
End If
StockDB = Nothing

' Reset the progress bars
'
f.ProgressBar_step.Value = 0
f.ProgressBar_overall.Value = 0

' Close the output files
'
closeOutputFiles()

' Skip a line on the display, blank out the status line
'
f.AddDisplayRecord("")

End Try

Here's the code that handles showing status to the user while this is going
on. It runs DoEvents() so some message pump is running while I'm inside my
OnClick handler.

Public Sub AddTimestampedRecord(ByVal newText As String)

' We want to both add to the listbox and scroll it if it was already
viewing
' the latest stuff. We don't scroll if the latest stuff was not in
the window,
' on the theory that the user is trying to look at history and we
don't want
' to prevent that.
'
Dim tsText As String
With Steps_ListBox
Dim atTop As Boolean = (.Items.Count - lbSizeCount) <= .TopIndex
tsText = DateTime.Now.ToString("HH:mm:ss.fff' -- '") & newText
Dim i As Integer = .Items.Add(tsText)
If atTop And i >= lbSizeCount Then
.TopIndex = i - lbSizeCount + 1
End If
End With

' If the run log file is open, write this text there too
'
If Not runLogFile Is Nothing Then
runLogFile.WriteLine(tsText)
End If

' Put the text on the status line also
'
StatusBar1.Text = newText

' Run the message pump to get the screen up-to-date
'
Application.DoEvents()

End Sub

No special problems in getting my code to work, just the usual issues of
figuring out how to code what I need to do ... :) Changing the Cancel code
to set a flag makes that part work fine, but the exception approach "should"
have worked as well, and it almost did. The exception handling did
everything it was supposed to, and a bit more ...

Tad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top