Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how to collect stack trace of program crash

Tags:

I am new to C#. I am writing a small desktop form based application and I need to have this feature in the app.

If the application crashes at any time, there should be a last opportunity for the app to collect stack trace and send it back to me...

Please give me directions on this.

Do I need a try catch covering the main the entry point of my app ?? or what is the best way to handle such things in a C# app.

thank you,

like image 248
Ahmed Avatar asked Apr 18 '12 04:04

Ahmed


People also ask

What does != Mean in C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is operators in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is the use of in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more.


2 Answers

To catch all unhandled exceptions, Add this to program.cs:

    [STAThread]     static void Main()     {     AppDomain currentDomain = default(AppDomain);     currentDomain = AppDomain.CurrentDomain;     // Handler for unhandled exceptions.     currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;     // Handler for exceptions in threads behind forms.     System.Windows.Forms.Application.ThreadException += GlobalThreadExceptionHandler;     ...     }  private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e) {    Exception ex = default(Exception);    ex = (Exception)e.ExceptionObject;    ILog log = LogManager.GetLogger(typeof(Program));    log.Error(ex.Message + "\n" + ex.StackTrace); }  private static void GlobalThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs e) {    Exception ex = default(Exception);    ex = e.Exception;    ILog log = LogManager.GetLogger(typeof(Program)); //Log4NET    log.Error(ex.Message + "\n" + ex.StackTrace); } 

Stack trace you can get by exception.StackTrace

like image 139
Aseem Gautam Avatar answered Sep 21 '22 15:09

Aseem Gautam


If I were you, I would consider an all-in-one solution, such as the free and open source NBug framework,

http://nbug.codeplex.com/

like image 31
Lex Li Avatar answered Sep 17 '22 15:09

Lex Li