Suppress unhandled exception dialog? - c#

I'm handling all of my unhanded exception in the code but whenever one happens (not during debugging) I get my error window and as soon as it closes "Unhandled application exception has occurred in your application" window pops up. How do I suppress it?
PS : I am not using ASP.NET , I'm using Windows Forms

You cannot suppress AppDomain.UnhandledException. Something really nasty happened, a thread in your program died from a heart attack. The odds that the program will continue to run in a meaningful way are zero, .NET puts an end to the misery by terminating the program.
Write an event handler for the AppDomain.CurrentDomain.UnhandledException event and log or display the value of e.ExceptionObject.ToString() so you know what caused the mishap. That gives you a hint how to fix your code. If any, it may well be something that you cannot fix yourself. Some kind of database server malfunction for example. Doing anything to intentionally hide the error is therefore a Very Bad Idea. Your customer's support staff will have no idea what to do.

For Windows Forms, you can send unhandled exceptions (that would otherwise cause the unhandled exception window to pop up) to your exception handler by adding the following in the Main() method, before the Application.Run() method is called:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
You can subscribe your handler to the unhandled exception event by adding the following to the form's constructor or elsewhere:
Application.ThreadException += myHandler;
And your form's handler method would look like this:
void myHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//do something
}
You can find more information about this on the msdn.

Here's a solution to show all unhandled exceptions, both managed and unmanaged types:
static void Main() {
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
}
catch (Exception ex) {
MessageBox.Show("A fatal error has occurred. Please contact your admin\n" +
"Exception type: " + ex.GetType() + "\n" +
"Exception Message: " + ex.Message + "\n" +
ex.StackTrace, "Fatal Exception");
if (ex.InnerException != null) {
MessageBox.Show("Inner Exception:\n" +
"Exception type: " + ex.InnerException.GetType() + "\n" +
"Exception Message: " + ex.InnerException.Message + "\n" +
ex.StackTrace, "Fatal Exception (inner)");
}
}
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
throw new Exception(e.Exception.Message, e.Exception);
}
To test this, I used C++/CLI to throw an unmanaged exception. These won't get caught properly unless the above Application_ThreadException Handler is present.

I would use exception shielding.
Windows App Example
This one shows use for Services
Exception Shielding
Its part of the enteprise library, and allows you to filter out exceptions as well as remap them, to hide the details.

Related

Should UnhandledException notify all unhandled exceptions? [duplicate]

I wanted to set some handler for all the unexpected exceptions that I might not have caught inside my code. In Program.Main() I used the following code:
AppDomain.CurrentDomain.UnhandledException
+= new UnhandledExceptionEventHandler(ErrorHandler.HandleException);
But it didn't work as I expected. When I started the application in debugging mode and threw an exception it did call the handler, but afterwards the exception helper in Visual Studio popped up as if the exception occurred without any handling. I tried Application.Exit() inside the handler but it didn't work as well.
What I would like to achieve is that the exception is handled with my handler and then the application closes nicely. Is there any other way to do it or am I using the code above in the wrong way?
Normally I use something like this to try and catch all unexpected top-level exceptions.
using System;
static class Program
{
[STAThread]
static void Main(string[] argv)
{
try
{
AppDomain.CurrentDomain.UnhandledException += (sender,e)
=> FatalExceptionObject(e.ExceptionObject);
Application.ThreadException += (sender,e)
=> FatalExceptionHandler.Handle(e.Exception);
// whatever you need/want here
Application.Run(new MainWindow());
}
catch (Exception huh)
{
FatalExceptionHandler.Handle(huh);
}
}
static void FatalExceptionObject(object exceptionObject) {
var huh = exceptionObject as Exception;
if (huh == null) {
huh = new NotSupportedException(
"Unhandled exception doesn't derive from System.Exception: "
+ exceptionObject.ToString()
);
}
FatalExceptionHandler.Handle(huh);
}
}
Maybe it is something you find helpful too? This main code routes all three ways of catching unexpected top-level exceptions through one method call. All you now need is a static class FatalExceptionHandler that includes your top-level exception handling in its Handle method.
And really, any application developer knows there are really just two things to do there:
Show/log the exception like you see fit
Make sure you exit/kill the application process
If you think item two is strange, remember that we only bother to do this in the first place for really exceptional situations. These things are probably bugs that need changes to your application to be accurately addressed. Any other exception handling - the functional kind - should be lower down inside your actual program code, catching specific kinds of exceptions where this makes sense and handling them there in the way that makes sense. Anything else should bubble up to your FatalExceptionHandler to make itself known and stop the possibly crippled program from working from corrupted state
Dead programs tell no lies... ;-)
It's because you're running it through Visual Studio in Debug mode. If you release and install your app somewhere else, nothing but your global exception handler will be processed.
Note that unhandled exceptions are still pretty fatal; you can only really use this for logging, or maybe some hasty close-down. Neither this nor Application.ThreadException can be used as a global sink for errors.
The better approach is to add proper handling - for example, around your entire Main() logic. Note that even this can't catch a few exceptions, such as errors during form-load (which get particularly nasty - you can catch them with a debugger attached, but not without).
Perhaps what you're looking for is Environment.Exit(int errorcode)
That behavior is by design.
But there is a work-around.
Either you call Process.GetCurrentProcess().Kill(); within the handler, or simply do not let the handler end.
Check out the example:
class Program
{
void Run()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Console.WriteLine("Press enter to exit.");
do
{
(new Thread(delegate()
{
throw new ArgumentException("ha-ha");
})).Start();
} while (Console.ReadLine().Trim().ToLowerInvariant() == "x");
Console.WriteLine("last good-bye");
}
int r = 0;
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Interlocked.Increment(ref r);
Console.WriteLine("handled. {0}", r);
Console.WriteLine("Terminating " + e.IsTerminating.ToString());
Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Name = "Dead thread";
while (true)
Thread.Sleep(TimeSpan.FromHours(1));
//Process.GetCurrentProcess().Kill();
}
static void Main(string[] args)
{
Console.WriteLine("...");
(new Program()).Run();
}
}
This should not be a default sink for exceptions, surely.
But this should be done to report exceptions gracefully.
Note: if you're application is a Windows Forms application, don't forget to:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
... or else the application will terminate, even if you handle the exceptions with the handlers specified by the other answers.

How to print the exception in Windows Phone?

I am trying to code an app for windows phone 8. I want to print the exception to the screen if I get any. So here is what I am doing:
try
{
//The code which I want to handle for exception
}
catch (Exception e)
{
ErrorStatus.Text = e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace;
}
where ErrorStatus is my TextBlock.
However, the only line in my catch block is giving me an exception during the runtime. The exception is:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Am I doing something wrong syntactically? I am new to C# programming as well as Windows Phone programming.
Edit:
More details of the exception:
System.UnauthorizedAccessException was unhandled by user code
HResult=-2147024891
Message=Invalid cross-thread access.
Source=System.Windows
InnerException:
You need to show your message from the UI thread: web calls always callback on a background worker thread. So, you need to call the Dispatcher to get this to run on the UI thread.
Also you can just use Exception.ToString() to show the message content as a string. This has the advantage of also showing any nested exceptions inside the one you're handling.
As a temporary measure try:
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ErrorStatus.Text = e.ToString();
}
}
More permanently you should either fix the issue or log it to a file so you aren't catching exceptions which are masking bugs in your code.
This is the best way to print out your exception message so that you may know where the problem is:
try{}
catch(Exception ex)
{
await new MessageDialog("Error message:\n\n" + ex.message).ShowAsync();
}

Show form when exception occurs C#

I have been looking at the Windows API Code Pack 1.1 and have seen a Error sample and would like to integrate it into my Application, the main idea would be for it to show if any error in the application happens, well not any but some that I choose.
How can I program this?
I am using WPF
Thanks
In the constructor of your App class add:
DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
then add a method to the App class similar to the following:
void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
if (MessageBox.Show("An unexpected error has occurred. You should exit this program as soon as possible.\n\n" +
"Exit the program now?\n\nError details:\n" + e.Exception.Message,
"Unexpected error", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
Shutdown();
}
You can have an catch block at the top-level of your program that will display the form with relevant error details. Or you can trap unhandled exceptions using the Application.UnhandledException (assuming you are using winforms), Application.ThreadException and AppDomain.UnhandledException.
If you want a message window to show up when any exception occurs, handled or not, then you will either have to explicitly write code in each catch block to show the form, or use something like PostSharp to weave in code that shows the form whenever an exception is thrown.
The following will catch all exceptions and display them in a messagebox:
[STAThread]
public static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
// work with exception
MessageBox.Show(e.Exception.Message);
}
Do note that if you're heavy into threading, you might want to test its behaviour with a thread-heavy application.
More information here.

c# console application - prevent default exception dialog

I have simple application with single AppDomain which is periodicaly launched on a server. Sometimes unhandled exception occurs in the aplication and default abort/retry/ignore dialog pops up. I need to somehow prevent the edialog from showing and just output the exception on StrErr and close the application. So I enclosed all the code in main method with try-catch statement, but it didn't help at all - the exception dialog is still shown sometimes.
The Main() code looks like this:
try
{
RunApplication();
}
catch (Exception exc)
{
Console.Error.WriteLine(exc.ToString());
Console.Error.WriteLine(exc.StackTrace);
if (exc.InnerException != null)
{
Console.Error.WriteLine(exc.InnerException.ToString());
Console.Error.WriteLine(exc.InnerException.StackTrace);
}
Environment.Exit(666);
}
This try-catch clause shoud catch all unhandled exceptions and the exception dialog should never popup AFAIK. Am I missing something? Or is there any setting (registry etc) on the server which controls some special behaviour related to the exception dialog/application error code?
There's an unhandled exception event you can subscribe to in the application domain.
public static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
//some code here....
}
/// <summary>
/// Occurs when you have an unhandled exception
/// </summary>
public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//here's how you get the exception
Exception exception = (Exception)e.ExceptionObject;
//bail out in a tidy way and perform your logging
}
Have you considered the possibility that your catch clause may be throwing exceptions?
Do you spawn threads in your main app?

Handling unhandled exceptions problem

I wanted to set some handler for all the unexpected exceptions that I might not have caught inside my code. In Program.Main() I used the following code:
AppDomain.CurrentDomain.UnhandledException
+= new UnhandledExceptionEventHandler(ErrorHandler.HandleException);
But it didn't work as I expected. When I started the application in debugging mode and threw an exception it did call the handler, but afterwards the exception helper in Visual Studio popped up as if the exception occurred without any handling. I tried Application.Exit() inside the handler but it didn't work as well.
What I would like to achieve is that the exception is handled with my handler and then the application closes nicely. Is there any other way to do it or am I using the code above in the wrong way?
Normally I use something like this to try and catch all unexpected top-level exceptions.
using System;
static class Program
{
[STAThread]
static void Main(string[] argv)
{
try
{
AppDomain.CurrentDomain.UnhandledException += (sender,e)
=> FatalExceptionObject(e.ExceptionObject);
Application.ThreadException += (sender,e)
=> FatalExceptionHandler.Handle(e.Exception);
// whatever you need/want here
Application.Run(new MainWindow());
}
catch (Exception huh)
{
FatalExceptionHandler.Handle(huh);
}
}
static void FatalExceptionObject(object exceptionObject) {
var huh = exceptionObject as Exception;
if (huh == null) {
huh = new NotSupportedException(
"Unhandled exception doesn't derive from System.Exception: "
+ exceptionObject.ToString()
);
}
FatalExceptionHandler.Handle(huh);
}
}
Maybe it is something you find helpful too? This main code routes all three ways of catching unexpected top-level exceptions through one method call. All you now need is a static class FatalExceptionHandler that includes your top-level exception handling in its Handle method.
And really, any application developer knows there are really just two things to do there:
Show/log the exception like you see fit
Make sure you exit/kill the application process
If you think item two is strange, remember that we only bother to do this in the first place for really exceptional situations. These things are probably bugs that need changes to your application to be accurately addressed. Any other exception handling - the functional kind - should be lower down inside your actual program code, catching specific kinds of exceptions where this makes sense and handling them there in the way that makes sense. Anything else should bubble up to your FatalExceptionHandler to make itself known and stop the possibly crippled program from working from corrupted state
Dead programs tell no lies... ;-)
It's because you're running it through Visual Studio in Debug mode. If you release and install your app somewhere else, nothing but your global exception handler will be processed.
Note that unhandled exceptions are still pretty fatal; you can only really use this for logging, or maybe some hasty close-down. Neither this nor Application.ThreadException can be used as a global sink for errors.
The better approach is to add proper handling - for example, around your entire Main() logic. Note that even this can't catch a few exceptions, such as errors during form-load (which get particularly nasty - you can catch them with a debugger attached, but not without).
Perhaps what you're looking for is Environment.Exit(int errorcode)
That behavior is by design.
But there is a work-around.
Either you call Process.GetCurrentProcess().Kill(); within the handler, or simply do not let the handler end.
Check out the example:
class Program
{
void Run()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Console.WriteLine("Press enter to exit.");
do
{
(new Thread(delegate()
{
throw new ArgumentException("ha-ha");
})).Start();
} while (Console.ReadLine().Trim().ToLowerInvariant() == "x");
Console.WriteLine("last good-bye");
}
int r = 0;
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Interlocked.Increment(ref r);
Console.WriteLine("handled. {0}", r);
Console.WriteLine("Terminating " + e.IsTerminating.ToString());
Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Name = "Dead thread";
while (true)
Thread.Sleep(TimeSpan.FromHours(1));
//Process.GetCurrentProcess().Kill();
}
static void Main(string[] args)
{
Console.WriteLine("...");
(new Program()).Run();
}
}
This should not be a default sink for exceptions, surely.
But this should be done to report exceptions gracefully.
Note: if you're application is a Windows Forms application, don't forget to:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
... or else the application will terminate, even if you handle the exceptions with the handlers specified by the other answers.

Categories