Displaying and writing C # exceptions
I have a C # program that outputs NullReferenceException()
. When I run this on my Vista machine, it gives the familiar "Foo has stopped working" screen. I can easily hit "details" to see what went wrong. On one XP machine there is no warning: the program simply exits, and on another XP I get the message "Foo has found the problem ...". Is there a way to change this setting (XP)?
Also, I would like this error message to be written to the log file so I can figure out what went wrong if someone else is using my program. Is there a way to send unused exceptions to a file?
edit: I want this for the whole project, not just the critical section. I didn't think it was recommended to use the whole program in bulk try...catch
, or is it?
a source to share
Take a look at: UnhandledException and ThreadException .
You can log errors to a file or use Windows logging tools .
You can also try this and this , it should point you in the direction you want to go. This post is about the same problem that you are trying to solve.
a source to share
If you are targeting WPF, you can use DispatcherUnhandledException
to catch any exception that you don't handle in your code. Otherwise, be sure to catch any observable exception with try-catch blocks.
In a delegate DispatcherUnhandledException
or in a section catch
of a try-catch block, you can call a function that writes an error message to a log file.
a source to share
See this link:
http://blogs.msdn.com/csharpfaq/archive/2006/03/27/562555.aspx
This will get you to work.
Using:
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));
}
a source to share
You can complete your code in
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 record object pointing to the log file of your choice.
If it is a winforms application, you can enable a message box or custom dialog informing the user of what happened as shown above.
a source to share