473,854 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

My application exits after handling an ApplicationExce ption

Hi,

I'm having limited luck getting an ApplicationExce ption 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
ApplicationExce ption 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 UserInterruptEx ception 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 2132
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 ApplicationExce ption 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
ApplicationExce ption 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 UserInterruptEx ception 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.Ena bleVisualStyles ()
Application.DoE vents()

' 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******** ********@tk2msf tngp13.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 ApplicationExce ption 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
ApplicationExce ption 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 UserInterruptEx ception 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 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

Nov 21 '05 #5

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

Similar topics

2
3496
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 sets it to zero, and only if the level reaches zero the commit/rollback statement is sended to the database. try { BeginTransaction(); // stuff
6
5235
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, that is a long long way from my presentation layer/aspx page, where I would at least like to print out a notification that an error was raised. How can I best achieve this in an n-tier environment. It seems if I handle the error in my Data Access...
14
1855
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 ????? OK, this function may return a boolean, and if this is true, then no message back is really required, but if it fails then some supporting message needs to be returned to the calling code. As I see it there are a few options.
8
6056
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 there a way I can compile the application such that it won't even attempt to launch without correct permissions instead of just crashing? Thanks for any help. -Mike
8
2151
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 class to write to files, databases, etc..., but I would really like to attach to running .NET processes and get the results without any logging and instead capture the real-time results when troubleshooting.
1
3035
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 having difficulties figuring out the best way to handle (catch) exceptions in the different layers and then propagating those errors back up through the call stack to ultimately display something to the end-user. Note this is an intranet...
3
1229
by: ben | last post by:
I have a custom exception class MyException: System.Runtime.InteropServices.COMException { ..... } and code like this try {
7
2607
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: Call the thread running the GUI "A". When user clicks a button a new thread "B" is created and started. "B" does a lots of work, among others transmitts data via a USB-CAN-interface. At the end of "B" a paper label is printed using methods provided...
12
1710
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 program with a random exit value, and without a handler set up, it crashes with a SIGSEGV, but as I have found out with gdb, at the same line of code: __libc_siglongjmp (env=0xbfb935f0, val=1) at longjmp.c:29 29 {
0
9899
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11023
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10672
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10740
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10362
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9509
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7909
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
3181
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.