473,614 Members | 2,076 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Handling top-level exceptions

It appears that exception handling at the top-most level of a C#
program, in the static void Main() method, differs depending on whether
the program is run in debug mode or not. That is, code such as the
following

try
{
Application.Run (new something());
}
catch
{
...
}
finally
{
...
}

invokes the catch{} handler (if an exception is thrown somewhere and is
not caught elsewhere) and the finally{} handler only when the program is
run in debug mode. At least, that is the behavior that I have observed.
How do you get the catch{} and finally{} handlers to be invoked
unconditionally , regardless of how the program has been launched?
Nov 17 '05 #1
3 3392
Without knowing how you are testing this it is impossible to determine
exactly why your results are skewed.

Given the snippet you show below, the catch handler will catch everything
that is thrown on the main thread, even if the exception is not
CLS-compliant (e.g. a library somewhere throws an integer rather then an
exception object). Also, since the catch block is a 'naked' catch, there is
no exception object associated with it, so you will be unable to examine the
cause of the exception.

It is important that you know which exceptions will not be caught;
exceptions thrown on any other thread will not be delivered to the catch
block. Examples of this include exceptions that occur on a threadpool
thread, a thread that you created manually, and also exceptions that occur
in finalizers, as the GC runs finalizers on a separate thread.

Exceptions thrown on the main thread and which are handled somewhere else
(i.e. further down the call stack another piece of code catches the
exception and handles/swallows it) will not be delivered to this catch
block.

Also, the catch handler will never be called unconditionally ...it will only
be executed if an exception occurs on that thread which is not handled
somewhere else.

The finally block will always execute unconditionally , with one
exception....if the application terminates abnormally the finally block will
not run. For example, if some other piece of code calls Environment.Exi t.
Under normal circumstances execution returns from the call to
Application.Run (), and from there execution always continues at the finally
block (or the catch block).

None of these behaviors depends on the type of build...debug versus release.
There are some differences that may show up in edge cases but which are not
likely to effect the code snippet you show below.

For example, the statement
Application.Run (new something());
causes an object of type 'something' to be created, but the reference is not
assigned to a local variable, so the shortest lifetime possible is scoped to
the method call to Run(). When running under the debugger the debugger
typically will report the reference as live until the end of the Main's
method body instead of the call to Run()...this makes it easier to debug as
you can examine the object even after the method call has been completed. In
the release build the object's lifetime may end after the call to Run
returns. If the object has a finalizer then in a release build it could be
run before the finally block that follows the Run(), or in a debug build it
may get called after the finally block runs.
"Robert Rotstein" <rr*******@veri zon.net> wrote in message
news:kh3Ze.2516 $lW3.811@trndny 09...
It appears that exception handling at the top-most level of a C# program,
in the static void Main() method, differs depending on whether the program
is run in debug mode or not. That is, code such as the following

try
{
Application.Run (new something());
}
catch
{
...
}
finally
{
...
}

invokes the catch{} handler (if an exception is thrown somewhere and is
not caught elsewhere) and the finally{} handler only when the program is
run in debug mode. At least, that is the behavior that I have observed.
How do you get the catch{} and finally{} handlers to be invoked
unconditionally , regardless of how the program has been launched?

Nov 17 '05 #2
I am running a debug build in both cases. If I run it with F5 (start),
then -- since the program is deliberately constructed to throw an
exception (this is a homework program) -- both the catch{} and the
finally{} are invoked. If the program is started with ctrl-F5 (start
without debugging), neither is reached; instead, a default system
handler is invoked, displaying an appropriate error message.

You can see a description of the homework assignment at
http://www.rollthunder.com/Harvard/homework/index.htm. This is the
second homework assignment. Note that the last sentence of the item no.
8 states: "Hint: Make sure you test the client program outside the
debugger as well as inside, the top-level exception behavior is
different.".
Nov 17 '05 #3
The way you phrased your statement made it appear you were referring to a
difference in the debug versus release builds - instead, you are seeing a
difference when running under a debugger versus when running from a command
line.

The different results you are seeing are not due to differences in the
underlying runtime - it behaves as I described. The difference is due
entirely to the way that the Windows.Forms class is written. That class
catches and deals with all exceptions itself that are not handled by the
event handlers it invokes. If you want to get notified when an exception has
occured that is caught by that handler you need to subscribe to the
Application.Thr eadException event. If you do not then you will get the
message box and then your app will terminate. All other unhandled exceptions
are delivered to the AppDomain.Unhan dledException handler (except for
asp.net exceptions). Personally, I believe they screwed up when the Forms
class was written did this - it would have been far less confusing to have a
single UE handler for all types of UEs (the AppDomain.UE). There is now a
completely artificial distinction between UEs and a code path that adds no
value IMO.

Anyway, you only get this behavior with the Windows.Forms class; there is
obviously some interaction with the debugger that causes the Forms class to
alter its runtime behavior wrt how it handles a UE.

If you create a simple console app you will see the "real" behavior of the
runtime. For example...

class Class1
{
static void Main(string[] args)
{
try
{
Trace.WriteLine ("In Main try block.");
new Class1().TestEx ception();
}
catch
{
Trace.WriteLine ("Exception caught in Main.");
}
finally
{
Trace.WriteLine ("In Main finally block.");
}
}

public void TestException()
{
throw new Exception("This is an uncaught exception.");
}
}

Regardless of how you run it the finally block will always execute, and the
catch block executes if an exception is thrown.
"Robert Rotstein" <rr*******@veri zon.net> wrote in message
news:togZe.600$ j_3.164@trndny0 7...
I am running a debug build in both cases. If I run it with F5 (start),
then -- since the program is deliberately constructed to throw an exception
(this is a homework program) -- both the catch{} and the finally{} are
invoked. If the program is started with ctrl-F5 (start without
debugging), neither is reached; instead, a default system handler is
invoked, displaying an appropriate error message.

You can see a description of the homework assignment at
http://www.rollthunder.com/Harvard/homework/index.htm. This is the second
homework assignment. Note that the last sentence of the item no. 8
states: "Hint: Make sure you test the client program outside the debugger
as well as inside, the top-level exception behavior is different.".

Nov 17 '05 #4

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

Similar topics

2
5758
by: Brian Idzik | last post by:
I've successfully setup a xhtml 1.0 strict page with Mozilla & Netscape to display links in a toolbar into an internal <div id='content'> within the same document. The toolbar uses some javascript, but mostly CSS class & id elements. Mozilla & Netscape work fine handling the toolbar submenus & contents, but IE6 misbehaves on several areas. On loading the page, the target div (id='content') will not display. When a menu item is...
5
4427
by: Frame | last post by:
I'm looking for tutorials or articles considering HTML Frames and how to handle them with Javascript. E.g. samples how Frames can exchange information, can a Frame instruct other Frame to update it's content etc. This kind of information is welcome. Cheers!
6
1646
by: vkreddy_in | last post by:
HI Currently i am handling excpetion using TRY/catch in my code.I am looking for solution some thing like this. if an excrption is occured then 1.call a CALLBACK function in a DLL 2.print the log message return from function call but excute the next instruction in the current function(when i return i want to go to the next instruction,not the instruction that was raised an exception)
13
1329
by: Michael B Allen | last post by:
This is a highly opinionated question but I'd like to know what people think in this matter. When initializing / creating a group of objects together I usually consolidate the error handling like the following: if (foo_init(&f) == -1 || (b = bar_new()) == NULL || some_function(a, b, c) == -1) { ERR(errno);
4
27932
by: m96 | last post by:
hi, i'm trying to make a query to a ldap server (version v2 or v3 doen't matter) with c#. the query works just fine but the problem is that i can't read the custom attributes/fields, since .net gives the following error: System.NotImplementedException: Handling of this ADSVALUE type is not yet implemented (type = 0xb). after googling for a long time i found out that many other have the same
12
2783
by: scsharma | last post by:
Hi, I am working on creating a webapplication and my design calls for creating main webform which will have menu bar on left hand side and a IFrame which will contain all the forms that are shown when menu items are clicked.Besides these i would like to put a custom status bar. Any error message encountered in any of the webpage will be displayed in the banner. The problem iam encountering is how to access the customer status bar in child...
3
1628
by: dhussong | last post by:
I'm trying to implement a generic exception handling routine that will write information to a text file at the time the exception occurred. I am using the Microsoft Application Block for Exception Handling to write to a text file. This is working great plus I get the call stack which is an added bonus. What I really want to get is the value of parameters and variables in each method in the call stack at the time of the exception. I know I...
3
4921
by: J055 | last post by:
Hi How do I tell the user he has tried to upload a file which is too big... 1. when the httpRuntime.maxRequestLength has been exceeded and 2. when the uploaded file is under then httpRuntime.maxRequestLength For point 1. it would be good to at least display a nice error page. IE seems to just display a blank page.
94
3202
by: Chad | last post by:
On to top of page 163 in the book "The C Programming Langauge" by K & R, they have the following: char *strdup(char *s) { char *p; p=(char *)malloc(strlen(s)+1); if( p != NULL) strcpy(p,s): return p;
8
1499
by: RichardOnRails | last post by:
I have a Stack class that works fine. In particular, when it encounters an error, it cout's a msg and exits. However, I'd like to change it to report the error and continue with dummy data as necessary. My problem is how to construct dummy data consistent with the type the class was instantiated with. My class, stripped to it's essentials for my purpose here, is: template <class T> class Stack {
0
8182
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
8130
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8627
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...
1
8279
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
7093
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
6088
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
5540
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();...
0
4052
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4127
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.