473,414 Members | 1,946 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,414 software developers and data experts.

exception handling



Hi

i have setup a global exception handler b4 Application.Run like
Application.ThreadException += new
ThreadExceptionEventHandler(GlobalExceptionProcess ing.AppThreadException
);

then after Application.Run(new Form1()); i have setup a global keyboard
hook

my problem is that if an error occured inside keyboardHookProc the
global exception error does not catch it

am i missing something?

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #1
13 2287
How about setting up a similar event handler for
AppDomain.UnhandledException ?

Nov 17 '05 #2
i though of that but could not find a way to make my application not die
after handling that event. Is it possible?

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #3
Why in the world would you want to set up a global exception handler?
You should catch exceptions relating to what failed, I don't think
you'll be able to effectively deal with thrown exceptions if you use
some one-size-fits-all technique common to old-school programming.

You can also "assume" that a good portion of the opcode will work, while
code that relies on unknown entities like remote servers etc, may
fail, and those you surround in try/catch... like

try
{
///myunknown routine here
}

catch (Exception ex)
{
Messagebox.Show(ex.message);
}

....like that. You shouldnt be using a single event handler for any
exception that gets thrown in the module.

tolisss wrote:

Hi

i have setup a global exception handler b4 Application.Run like
Application.ThreadException += new
ThreadExceptionEventHandler(GlobalExceptionProcess ing.AppThreadException
);

then after Application.Run(new Form1()); i have setup a global keyboard
hook

my problem is that if an error occured inside keyboardHookProc the
global exception error does not catch it

am i missing something?

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #4
Hi,

While I cannot give you an answer of why it happen I can give you ideas of
how to workaround it.

What if you use a try/catch block inside the hook, if you detect an
exception you could call GlobalExceptionProcessing.AppThreadException
( I think it's a static method , right ? )
Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"tolisss" <no****@devdex.com> wrote in message
news:Ov**************@TK2MSFTNGP14.phx.gbl...


Hi

i have setup a global exception handler b4 Application.Run like
Application.ThreadException += new
ThreadExceptionEventHandler(GlobalExceptionProcess ing.AppThreadException
);

then after Application.Run(new Form1()); i have setup a global keyboard
hook

my problem is that if an error occured inside keyboardHookProc the
global exception error does not catch it

am i missing something?

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #5
In order to have your application "not die," you must catch events
specifically where they happen and handle them there. Once an exception
has made it up the stack to a global event handler like
Thread.ThreadException or AppDomain.UnhandledException, there is no way
to indicate that you want to "go back" to where the exception
originally occurred and continue execution from that point.

All that these global event handlers do for you is give you the
opportunity to handle the unhandled exceptions in your own way before
your application dies, rather than settling for the default behaviour:
for example, inserting code to log the exceptions to a file. They don't
give you the opportunity to control where your application continues
execution, so far as I know.

Nov 17 '05 #6
Hi,

AFAIK there is no way to prevent the application from finishing. All you can
know is IF the application is finishing or not , IIRC if it's a worker
thread the app does not ends.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"tolisss" <no****@devdex.com> wrote in message
news:OR**************@tk2msftngp13.phx.gbl...
i though of that but could not find a way to make my application not die
after handling that event. Is it possible?

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #7
> Why in the world would you want to set up a global exception handler?
You should catch exceptions relating to what failed...

Absolutely not. You should catch exceptions that you know how to deal
with in your local code. For example, if you're trying to convert a
string to a double, and you know it might fail, but you have a default
value, you should catch the exception, set the default value, and allow
execution to continue.

Another example: if you try to call a Web Service and the call fails,
and that particular call isn't critical to your application, you could
catch the exception, warn the user that some information is not
available, and continue execution.

Global event handlers are for all of those other exceptions: the ones
that you can't handle gracefully... the ones that will kill your
application. A global event handler at least lets you tell the user
nicely that something has gone horribly wrong and you have to shut down
now. For example, we use them to display what we want the user to see
(in a MessageBox) but log the gory details to a log file for analysis
by the IS department.

Again, these are exceptions for which the application has no recovery
strategy, and so has to shut down. You should allow them to go
unhandled, and catch them in the global exception handler in order to
do user-friendly things in such a failure situation.
try
{
///myunknown routine here
}
catch (Exception ex)
{
Messagebox.Show(ex.message);
}


This is wrong on two counts. First and most aggrevious, it shows an
exception message to the user (is that going to mean anything to the
user?) and then _merrily carries on_ executing the program, even
thought the "myunknownroutine" _failed_ with an exception! How do you
know that the application _can_ continue functioning if that routine
fails? Is the state of the application such that it can survive that?
Or is everything in an indeterminate state now, a state that will
result in (at best) further exceptions or (at worst) subtle corruption
of your company's database?

The only way you should ever do this is if you _know_ that
"myunknownroutine" really isn't all that important, and if it fails
it's no big deal. In that case, yes, you should catch the exception,
and either silently log it to a file somewhere, or log it to a file and
warn the user that things are less than optimal, but the program can
still keep working.

The second reason that this is wrong is that you should avoid
catch-alls like "catch (Exception ex)". Carrying on with the idea that
you should only catch exceptions that you know are no big deal, do you
really know that _every exception_ that "myunknownroutine" could
possibly throw is no big deal? What about OutOfMemoryException? Do you
really want to catch that one and continue as though nothing happened?
What about InvalidArgumentException, which indicates an error in your
calling code? What if you verify that every exception is, in fact, no
big deal, but then the next revision of the library adds a new
exception? In general, you should catch _specific exceptions_ that you
know you can deal with, and let the other ones go.

There is one situation I've found, though, in which "catch (Exception
ex)" is inevitable. That's when a vendor's documentation about what
exceptions a method throws is lacking. (See the MSDN documentation on
the Crystal .NET stuff for an example of crap doc that doesn't tell you
_anything_ about exceptions.) In cases like this, you really have no
idea which exceptions a method will throw, so you either have to run
some tests and figure out which exceptions you can handle, or decide
that it's no big deal if the method fails and just do "catch (Exception
ex)". I, for example, use this catch-all and just inform the user that
the report couldn't be printed, and then move on. That's one case in
which a method failure is not a problem.

Global exception handlers are not "old-school programming": they are
the recommended way of gracefully shutting down an application that has
failed.

Nov 17 '05 #8
Bruce Wood wrote:
Absolutely not. You should catch exceptions that you know how to deal
with in your local code. For example, if you're trying to convert a
string to a double, and you know it might fail, but you have a default
value, you should catch the exception, set the default value, and allow
execution to continue.


Dealing with say, an unavailable resource is a lot like the application
not working at all if it depends on that resource... we catch what we
think may give us an error...

I don't have anything against a clean exit if there is an error that we
don't know what to do with, but I question how the framework may handle
that exception by default... an error message from the framework with
MSIL may not be much worse than a custom error message based on the
thrown exception we have caught.
Nov 17 '05 #9
Bruce Wood wrote:
Absolutely not. You should catch exceptions that you know how to deal
with in your local code. For example, if you're trying to convert a
string to a double, and you know it might fail, but you have a default
value, you should catch the exception, set the default value, and allow
execution to continue.


Dealing with say, an unavailable resource is a lot like the application
not working at all if it depends on that resource... we catch what we
think may give us an error...

I don't have anything against a clean exit if there is an error that we
don't know what to do with, but I question how the framework may handle
that exception by default... an error message from the framework with
MSIL may not be much worse than a custom error message based on the
thrown exception we have caught.
Nov 17 '05 #10
Usually global exception handlers are used only to log the detailed
message (such as a stack trace or other such information) in a central
log while showing the user a message that says simply, "Something went
wrong. Please contact the IT department."

Generally this is either to make the application look more
professional, or for security reasons (not wanting to publicize the
internal details of your application's architecture in an error
message).

There's really not much else you can do in an global exception handler.
You can't tell the application to continue in any meaningful way (it's
effectively already dead), so they're useful only for logging (and thus
dealing gracefully) with catastrophic errors.
Dealing with say, an unavailable resource is a lot like the application not working at all if it depends on that resource... we catch what we think may give us an error...


For any exception, there are really only three cases that I can think
of:

1. The exception indicates a situation from which the application can
reliably recover. A conversion error, a format error, an unavailable
resource that is not critical to the application. In this case, you
_should_ catch the exception, take remedial action, and continue
execution.

2. The exception is one that you can't do anything about at all.
OutOfMemoryException is a good example of this. Don't try to catch the
exception. Let it bubble to the top of the stack and into the global
exception handler. Log it or report it as you wish, and take the
application down.

3. The exception is one that you can't do anything about, but if you
just let it bubble up the stack you will lose valuable contextual
information about what went wrong and the resulting error message,
logged or not, will be next to useless. Catch the exception, log the
appropriate contextual information, then rethrow the exception, or
throw a more meaningful exception that wraps the original exception,
and let that exception bubble up the stack and into the global
exception handler.

This is why most C# programs are full of try...finally blocks, with no
catches. The finally releases resources and does other cleanup if
something fails, but there is no attempt to catch the exceptions, as
there's really nothing useful to do with them at that point in the
code.

At least for the time being (and, given Anders Hejlsberg's outlook on
this probably forever) the C# model of how to deal with exceptions is
very, very different from the Java model. I won't go into how Java
deals with exceptions, but it's a whole different take on the thing. C#
(and .NET in general) encourages more global exception handling, while
Java encourages more local exception handling. After getting used to
the C# way, I have to say that I prefer it (with some caveats).

Nov 17 '05 #11


Bruce Wood wrote:

[lots of stuff]

Amen!
There is one situation I've found, though, in which "catch (Exception
ex)" is inevitable. That's when a vendor's documentation about what
exceptions a method throws is lacking. (See the MSDN documentation on
the Crystal .NET stuff for an example of crap doc that doesn't tell you
_anything_ about exceptions.) In cases like this, you really have no


I rather like to have:

try {
...;
} catch ( Exception e ) {
LogFatalException(e);
throw;
}

at the top of the call-stack.

Of course, Log should preferably not throw any expections itself :)

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #12
Thanks for the terrific response Bruce. It certainly gives one something
to consider when designing on an every day basis, usable, stable, at
least hopfully logical modules.

~Michael.

Bruce Wood wrote:
For any exception, there are really only three cases that I can think
of:

1. The exception indicates a situation from which the application can
reliably recover. A conversion error, a format error, an unavailable
resource that is not critical to the application. In this case, you
_should_ catch the exception, take remedial action, and continue
execution.[....]

Nov 17 '05 #13
You're welcome. It occurred to me this morning that on point #3,
exceptions that you can't do anything about, but which should have more
contextual information logged in order to make them useful, you can
also catch the exception, and then throw a new exception that wraps the
original exception, _and adds contextual information_ in the new
exception's message. You can then let the new exception bubble up the
call stack and into the global exception handler, where it will be
logged, along with all of the contextual information it contains.

I do this in several spots, especially when I discover during debugging
that an exception isn't very informative and I need more information
about what happened.

Nov 17 '05 #14

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

Similar topics

11
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses...
6
by: Daniel Wilson | last post by:
I am having exception-handling and stability problems with .NET. I will have a block of managed code inside try...catch and will still get a generic ..NET exception box that will tell me which...
7
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
3
by: Master of C++ | last post by:
Hi, I am an absolute newbie to Exception Handling, and I am trying to retrofit exception handling to a LOT of C++ code that I've written earlier. I am just looking for a bare-bones, low-tech...
2
by: tom | last post by:
Hi, I am developing a WinForm application and I am looking for a guide on where to place Exception Handling. My application is designed into three tiers UI, Business Objects, and Data Access...
9
by: C# Learner | last post by:
Some time ago, I remember reading a discussion about the strengths and weaknesses of exception handling. One of the weaknesses that was put forward was that exception handling is inefficient (in...
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
4
by: Ele | last post by:
When Exception handling disabled compiler still spits out "C++ exception handler used." Why is that? Why does it ask for "Specify /EHsc"? Thanks! c:\Program Files\Microsoft Visual Studio...
41
by: Zytan | last post by:
Ok something simple like int.Parse(string) can throw these exceptions: ArgumentNullException, FormatException, OverflowException I don't want my program to just crash on an exception, so I must...
1
by: George2 | last post by:
Hello everyone, Such code segment is used to check whether function call or exception- handling mechanism runs out of memory first (written by Bjarne), void perverted() { try{
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
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...
0
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...
0
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...

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.