473,387 Members | 3,801 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

My application exits after handling an ApplicationException

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
Nov 21 '05 #1
4 2096
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.

Tad Marshall wrote:
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

Nov 21 '05 #2
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
Nov 21 '05 #3
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

"Adam Goossens" <ad***********@gmail.com> wrote in message
news:%2****************@tk2msftngp13.phx.gbl...
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.

Tad Marshall wrote:
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


Nov 21 '05 #4
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

Nov 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: cody | last post by:
Is this good style? I always have to catch the generic System.Exception because our system supports nested transactions that is BeginTransaction increases the level, Commit decreases it, rollback...
6
by: Raterus | last post by:
Hello, I'm trying to hop on the n-tier/OOP bandwagon for my applications, but I've hit one snag that I'm not sure the best way to proceed. Say a SqlException is raised in my Data Access layer,...
14
by: Mr Newbie | last post by:
I am often in the situation where I want to act on the result of a function, but a simple boolean is not enough. For example, I may have a function called isAuthorised ( User, Action ) as ?????...
8
by: mike2036 | last post by:
I have an application (that has unmanaged code) and when I launch it without 'FullTrust' permissions (LocalIntranet_Zone), it crashes. When I set 'FullTrust' permissions, it launches fine. Is...
8
by: Bryan | last post by:
Does anyone have an example of an application that can connect to a running process and capture Trace.WriteLine calls like in SQL Server Profiler? I know that we can inherit from a TraceListener...
1
by: metsys | last post by:
We have an ASP.NET 2.0 (C#) application that is divided into multiple layers. The multiple layers come from having a web project and 2 different class library projects in the same solution. I'm...
3
by: ben | last post by:
I have a custom exception class MyException: System.Runtime.InteropServices.COMException { ..... } and code like this try {
7
by: Daniel | last post by:
Hello! I am having a problem with a windows application that abnormally terminates itself. The application is a multi threaded .NET 1.1 application, and can briefly be described as follows: ...
12
by: Fabiano Sidler | last post by:
Hi folks! I'm using gcc 4.2.3 and glibc6 2.7. I'm doing an exception handling implementation for a library. Although I assume to have it done properly, with a handler set up, it exits the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.