Unhandled Exception in Console Application

A

AG

Can anyone point me to an example or info on handling unhandled exceptions
in a console application?
Preferrably VB.

Thanks,
 
A

AG

That enables me to log the exception, but how can I prevent the Windows
'Myapp has encountered a problem and needs to close...' dialog from popping
up?
 
L

Luc E. Mistiaen

you can try
if (Args.IsTerminating) Environment.Exit (0) ;

where Args is your UnhandledExceptionEventArgs

/LM
 
A

AG

Thanks both.
That works.
I haven't done a console app before and It is a very small one. I could
easily have wrapped that whole thing in a try/catch, but this way I learned
much more :).
 
J

Jeroen Mostert

Luc said:
you can try
if (Args.IsTerminating) Environment.Exit (0) ;

where Args is your UnhandledExceptionEventArgs
Be aware that this technique does not scale to services or multiple
appdomains, and it will also prevent you from diagnosing the unhandled
exception under a debugger (you can set a breakpoint on the event callback,
but that isn't convenient at all). Finally, the usual step of writing an
error to the event log will be skipped.

I also suggest passing a non-zero value to Environment.Exit(), since
processes that check the exit status (if any) will usually interpret a zero
exit status as success, which is a tad misleading.

In short, I'm not at all happy that this actually works. :)
 
A

AG

Thanks for the info.
In this case it will be fine as the app is just for my own use.
However, I am interested in how you think it should be handled.
 
L

Luc E. Mistiaen

Finally, the usual step of writing an error to the event log will be

I suppose it was precisely waht the OP intended to do: his own logging. You
just do it before exiting.
I also suggest passing a non-zero value to Environment.Exit(), since
processes that check the exit status (if any) will usually interpret a
zero exit status as success, which is a tad misleading.

Of course, it was just an example.
In short, I'm not at all happy that this actually works. :)

Neither me, but its the only way I found to suppress the unwanted pop-up. I
would have much preferred some boolean to be set in the argument object to
tell the run-time I handled to event to my taste (knowing that the program
would terminate anyway).

/LM
 
L

Luc E. Mistiaen

Of course, this assumes the exception is happening somewhere that you are
unable to provide your own try/catch block in order to handle the
exception. Your original question implies this, but if it's not really
true, then obviously the best solution is to actually handle the
exception. :)

Yes, this really should be used as a last chance to log a catastrophic
unrecoverable error...

/LM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top