Catch all exception in C# winform application

application level exception handling in c#
c# catch all exceptions in application
global exception handler c#
unhandled exception c#
c# catch multiple exceptions
c# exception message
try catch finally c#
catching all exceptions

in C# winform desktop application I'm trying to catch all exceptions possible to appear in the code, what I've tried:

  using System;
    using System.Threading;
    using System.Windows.Forms;

    namespace Controller
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                Application.Run(new Form1());
            }

            static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
            {
                MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
            }

            static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");           
            }
        }
    }

I test it with attaching of "COM6" with form closing event without serial port in Device Manager, but I see only Visual Studio An exception of type 'System.InvalidOperationException' occurred in System.dll but was not handled in user code report

How it is possible to collect errors data for winform application

catch all the errors in one single point in your application is not a best practice. I suggest you to identify where your code may fails and use try/catch block to catch specific groups of errors instead. In this way you can control more better your application and you can identify more better the weaknesses of your code. For example:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {

    try{
      //Put here your code
    }
    catch{
    }
}

A generic "Exception" for sure can't help you or the user to identify a possible error in the application

What is an Unhandled Exception, and How to Catch All C# Exceptions, Also learn how to find catch all C# exceptions. NET Runtime error and another more generic Windows Application Error. From the . How to Catch All Exceptions in C# & Find All Application Errors Catching "First Chance Exceptions". If you want to find and catch every single exception in your ASP.NET Exception Handling. For ASP.NET web applications, you won’t prevent users .NET Framework Exception Events. The .NET

You can use try-catch to catch the exceptions in all methods. Inside catch you can log the reason for the exception.

try
{
   // Your code that might throw an error
}
catch( Exception e )
{
   // What you want to do when the error is thrown
   Logger.WriteException(e);
}

I would prefer writing a static class 'Logger' and 'WriteException' method for logging the exceptions to a text file.

public static class Logger
{
    public static void WriteException(Exception exception)
    {
        string filePath = @"D:\Error.txt";

        using (StreamWriter logWriter = new StreamWriter(filePath, true))
        {
            logWriter.WriteLine("Message :" + exception.Message + "<br/>" + Environment.NewLine + "StackTrace :" + exception.StackTrace +
               "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            logWriter.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
        }
    }
}

There are several error logging methods available , you can use the suitable one for your application. You can use EventLog, Microsoft Logger etc.

Catch all exception in C# winform application, catch all the errors in one single point in your application is not a best practice. I suggest you to identify where your code may fails and use  It sets SetUnhandledExceptionMode so that all exceptions are handled by the application, regardless of the settings in the application's user configuration file. It uses the ThreadException event to handle UI thread exceptions, and the UnhandledException event to handle non-UI thread exceptions.

Thas actually not that hard to do. I would advise to put any code for handling the exception into the mainform to keep the program.cs as clean as possible.

First in your Program.cs put this

static class Program
{
    public static Form MainForm = null;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.ThreadException += Application_ThreadException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        MainForm = new Form1();
        Application.Run(MainForm);
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        ((Form1)MainForm).Application_ThreadException(sender, e);
    }
}

Then in your mainform put this

    public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        // All unhandled exceptions will end up here, so do what you need here

        // log the error
        // show the error
        // shut the application down if needed
        // ROLLBACK database changes 
        // and so on...
    }

Application.SetUnhandledExceptionMode Method (System , Instructs the application how to respond to unhandled exceptions. C# Copy. Thread newThread = null; // Starts the application. It is often not feasible to catch all of the exceptions thrown by Windows Forms. Using this method, you can​  Always try/catch(Exception) your event handler code; this will protected your UI being always usable. For performance hit, performance penalty only happens when the code reachs catch, executing try code without the actual exception raised has no significant effect. Exception should be happened with little chance, otherwise it's not exceptions.

Defining Unhandled Exceptions and Catching All C# Exceptions , Learn what an unhandled exception is, as well as how to catch C# NET Runtime error and another more generic Windows Application Error. In applications that use Windows Forms, unhandled exceptions in the main application thread cause the Application.ThreadException event to be raised. If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state.

How can I catch all the exceptions that will be thrown through , . For example, When you try to open a file on disk, it is a common problem for the file to not exist. The . NET Framework will then throw a FileNotFoundException. Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, re-throw it using the throw keyword at the end of the catch block. If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.

Difference between System Level Exception and Application Level , NET. In a windows form application, the equivalent global catch all is available by listening to the ThreadException and AppDomain UnhandledException events. [​  An unhandled exception occurs when the application code does not properly handle exceptions. For example, When you try to open a file on disk, it is a common problem for the file to not exist. The .NET Framework will then throw a FileNotFoundException.

Comments
  • As soon as an unhandled run-time error is encountered, execution stops. Unless you're reporting the error and letting it continue, you won't see any additional errors because the application has stopped running.
  • Hello, yes I use catching of exception for any possible case, but if it is available to get common report for all cases, what exactly message content should be, how to handle this event
  • Hello, yes this way I'm storing data for each particular exception case, but I'm wondering, if it is possible to get single event with common report for any other possible cases, provided or not provided by each individual exception condition already exist in separate functions
  • Hello, I have tried this but same, I see only Visual Studio report with exception case like An exception of type 'System.InvalidOperationException' occurred in System.dll but was not handled in user code with same serial port test and MessageBox.Show inside the Application_ThreadException, which I've added below public Form1() in Form1.cs
  • This will only catch unhandled execptions. It is possible that a library catches an exception and shows this info using a messagebox.show. In that case you will never catch it anymore because it was already catched elsewhere