Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does that exception management code stinks?

Tags:

c#

exception

Why it is not advised (in a best pratice meaning) to manage all the exceptions of a system from the entry point.

class Program
    {
        static void Main(string[] args)
        {
              try
              {
                 [...]//all the program stuff
              }catch(Exception ex)
              {
                    [...]
              }
        }
    }

edit : in a second point does it change something for the performance?

like image 339
Christophe Debove Avatar asked Feb 19 '26 21:02

Christophe Debove


2 Answers

It's not advised in the meaning that you should catch exceptions in places where you can actually handle them in a useful way.

If there is nothing you can do about the exception but crash, your solution works, but consider for example a missing file giving you an exception. Would you rather handle it with a dialog in the "OpenFile" method (or in this case maybe the part of the method where you open the file) and possibly give the user a chance to browse to where the file is before proceeding, or would you rather have it throw back to main and have no real option except "log and crash"?

like image 181
Joachim Isaksson Avatar answered Feb 21 '26 11:02

Joachim Isaksson


This approach:

  • Doesn't emphasise catching expected exceptions in the right place, i.e. where they can be dealt with in the same context that they happened.
  • Won't catch an exception on another thread, so it won't work in a mutli-thread environment.
  • Won't catch many Windows Forms exceptions, as they're intercepted by the .NET Framework.
  • Swallows every exception, except when the process is corrupted. This isn't a good approach because you shouldn't swallow an exception when you don't understand it.

A better approach is to catch expected exceptions in the context-specific method, where the most knowledge is available for them to be handled properly. To catch unexpected exceptions, your Main method might look something like this:

// Event handler for handling all UI thread exceptions.
Application.ThreadException += 
    new ThreadExceptionEventHandler(App_UiThreadException);

// Force all Windows Forms errors to go through our handler.
// NB In .NET 4, this doesn't apply when the process state is corrupted.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Event handler for handling all non-UI thread exceptions. 
AppDomain.CurrentDomain.UnhandledException += new 
    UnhandledExceptionEventHandler(App_NonUiThreadException);

// Run the application. 
like image 35
HTTP 410 Avatar answered Feb 21 '26 11:02

HTTP 410



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!