Frank Meulenaar
Frank Meulenaar

Reputation: 1219

Displaying and capturing c# exceptions

I have a c# program which throws a NullReferenceException(). When I start this on my Vista machine, it gives the familiar screen "Foo has stopped working". I can easily click on 'details' to see what went wrong. On one XP machine there's no warning at all: the program just quits, and on another XP I get the "Foo has encountered a problem..." message. Is there a way I can change this (XP's) setting?

Furthermore, I would like to have this error message written to a log file, so I can see what went wrong if somebody else uses my program. Is there a way I can send the uncaught exceptions to a file?

edit: I want this for my entire project, not just for a critical section. I didn't think it is recommended practice to wrap the entire program in a big try...catch, or is it?

Upvotes: 2

Views: 183

Answers (5)

user346173
user346173

Reputation: 21

Add try catch blocks around all components that you think will fail and handle these by streaming the error data to your log file

Upvotes: 1

Francisco Soto
Francisco Soto

Reputation: 10392

Take a look at : UnhandledException and ThreadException.

You may log the errors in a file, or use Windows logging facilities.

You may also try this and this, it should point you in the direction you want to go. It's a post about the exact same problem you are trying to solve.

Upvotes: 3

Matt
Matt

Reputation: 4127

You could wrap up your code in a

try
{
    // Your code
}
catch (Exception ex)
{
    streamWriter.WriteLine("your custom exception text, stack trace:" + ex.StackTrace.ToString());
    MessageBox.Show("Your custom exception text, Stack Trace:" + ex.StackTrace.ToString());
}

and handle the feedback yourself with a stream writer object pointing to a log file of your chosing.

If its a winforms app you could include a message box or custom dialogue informing the user of what happened as shown above.

Upvotes: 0

luvieere
luvieere

Reputation: 37534

If you're targeting WPF, you can use the DispatcherUnhandledException to catch any exception that you don't handle in code. Otherwise, make sure to catch any foreseeable exception with try-catch blocks.

Either in DispatcherUnhandledException's delegate or in the catch section of a try-catch block, you can then call a function that writes the error message to a log file.

Upvotes: 1

Neil Knight
Neil Knight

Reputation: 48587

See this link:

http://blogs.msdn.com/csharpfaq/archive/2006/03/27/562555.aspx

This will get you up and running.

Use:

try
{
    // Your code here
}
catch (Exception ex)
{
    // This will tell you the Exception
    Console.WriteLine("Exception type: {0}", ex.GetType());
    // or, if you use the example from the link above
    LogMessageToFile(String.Format("Exception type: {0}", ex.GetType));
}

Upvotes: 0

Related Questions