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
"Cor Ligthert" <no************@planet.nl> wrote in message
news:OX**************@TK2MSFTNGP09.phx.gbl...
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