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 ApplicationExce ption 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 UserInterruptEx ception
Inherits ApplicationExce ption
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal exceptionText As String)
MyBase.New(exce ptionText)
End Sub
Public Sub New(ByVal exceptionText As String, ByVal inner As Exception)
MyBase.New(exce ptionText, inner)
End Sub
Here's where I throw the exception:
Private Sub Close_Cancel_bu tton_Click(ByVa l sender As System.Object, _
ByVal e As System.EventArg s) Handles Close_Cancel_bu tton.Click
' The Cancel button interrupts a walk, the Close button exits the
program
'
If inProgress Then
Throw New UserInterruptEx ception("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
'
createOutputFil es()
' Initialize the variables we'll need for this procedure
'
initializeVaria bles()
' Create our SQL Connection
'
f.AddTimestampe dRecord("Openin g Stocks database")
StockDB = New SqlConnection(" Data Source=localhos t;" & _
"Integrated Security=SSPI;I nitial Catalog=Stocks" )
' Build SQL text to pull in the data we want
'
cmd = StockDB.CreateC ommand()
cmd.CommandText = "SELECT " & _
<huge select statement trimmed to save space>
"ORDER BY TradeDate, PERMNO"
' Open the table
'
f.AddTimestampe dRecord("Sendin g SQL command: """ &
cmd.CommandText & """")
StockDB.Open()
' Run the data reader
'
f.AddTimestampe dRecord("Execut ing the reader")
reader = cmd.ExecuteRead er
' 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.GetValue s(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.GetUppe rBound(1) Then
Throw New ApplicationExce ption("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 UserInterruptEx ception
f.cancelPressed = True
Catch ex As Exception
f.AddTimestampe dRecord("Except ion: " & ex.Message)
Finally
' Note if Cancel was pressed, then clear the flag
'
If f.cancelPressed Then
f.AddTimestampe dRecord("Proces s 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.AddTimestampe dRecord("Closin g the reader")
If Not reader Is Nothing Then
reader.Close()
End If
reader = Nothing
f.AddTimestampe dRecord("Closin g the database")
If Not StockDB Is Nothing Then
StockDB.Close()
End If
StockDB = Nothing
' Reset the progress bars
'
f.ProgressBar_s tep.Value = 0
f.ProgressBar_o verall.Value = 0
' Close the output files
'
closeOutputFile s()
' Skip a line on the display, blank out the status line
'
f.AddDisplayRec ord("")
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 AddTimestampedR ecord(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.To String("HH:mm:s s.fff' -- '") & newText
Dim i As Integer = .Items.Add(tsTe xt)
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.Writ eLine(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.DoE vents()
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******** ******@TK2MSFTN GP09.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