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?
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"?
This approach:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With