Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is try/catch around whole C# program possible?

Tags:

A C# program is invoked by:

Application.Run (new formClass ()); 

I'd like to put a try/catch around the whole thing to trap any uncaught exceptions. When I put it around this Run method, exceptions are not caught; control only returns here when the program terminates after an uncaught exception.

Where can I put try/catch to cover the whole program? Thanks!

like image 452
user20493 Avatar asked Oct 21 '09 14:10

user20493


People also ask

Do we have try catch in C?

Yes, it is limited to one try-catch in the same function.

Should I use try catch everywhere C#?

No, you should not wrap all of your code in a try-catch.

Do try catch Objective C?

Exception handling is made available in Objective-C with foundation class NSException. @try − This block tries to execute a set of statements. @catch − This block tries to catch the exception in try block.


2 Answers

To catch Windows Form's unhandled exceptions hook-up the AppDomain.UnhandledException and Application.ThreadException events.

Of interest: Unexpected Errors in Managed Applications

like image 113
Mitch Wheat Avatar answered Oct 23 '22 08:10

Mitch Wheat


Basically, you cannot catch all exceptions when using the default CLR hosting process. Period. This is because the AppDomain.UnhandledException event is a notification only, you cannot handle the exception (which means that you cannot prevent the application from being terminated after processing the notification).

However, you can catch and handle all exceptions in the UI thread of a WinForms application by using its Application.ThreadException handler (and control the behavior via UnhandledExceptionMode). Other threads which throw an exception will not be caught by this handler.

In general, it's not a good idea to try and handle all exceptions. You can, however, use the AppDomain.UnhandledException to log the error and/or perform important cleanup tasks (e.g. shutting down a file-based databaseor whatever).

like image 29
Lucero Avatar answered Oct 23 '22 08:10

Lucero