2

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?

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Is this recommended practice?
Thanks for the links, they look interesting... (there's a typo in the first one)
I was about to post the same, hehe. (Answer, not typo hint :D)
1

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.

Comments

1

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

Comments

0

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)); } 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.