Yes. You can capture it for the purposes of logging it, but can not recover
from it
as well you shouldn't want to because if it was unhandled then you probably
are
not in a stable position to continue. The following code will catch the
unhandled
error and log it to a file, then continue to abort the application.
public class BaseException : Exception, ISerializable
{
public BaseException ()
: base ()
{
}
public BaseException ( string message )
: base ( message )
{
}
public BaseException ( string message, Exception innerException )
: base ( message, innerException )
{
}
protected BaseException ( SerializationInfo info, StreamingContext context )
: base ( info, context )
{
}
}
public sealed class UnhandledExceptionHandler : BaseException
{
public UnhandledExceptionHandler ()
: base ()
{
}
/// <summary>
/// Catches and logs any unhandled exceptions throw in the application.
/// Does NOT handle the error and proceed. The application will still
terminate, but
/// the reasons for the termination will be logged for further review.
/// </summary>
/// <param name="sender"></param>
/// <param name="t"></param>
/// <example>
/// Before Application.Run add the following lines
/// <code>
/// UnhandledExceptionHandler eh = new UnhandledExceptionHandler();
/// AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler ( eh.OnThreadException );
/// </code>
/// </example>
public void OnThreadException ( object sender, UnhandledExceptionEventArgs
t )
{
//Write the information to a log file.
// OpenOrCreateFile is a company method, it just opens a stream after
ensuring it doesn't exist etc.
using ( System.IO.StreamWriter sw = OpenOrCreateFile (
@"C:\UnhandledButCaughtErrors.txt", false ) )
{
Exception ex = null;
sw.Write (
"\r\n====================================================\r\n" );
sw.Write ( sender.ToString () + "\r\n" );
sw.Write ( "Caught Error on " + DateTime.Now + "\r\n" );
try
{
ex = (Exception)t.ExceptionObject;
}
catch
{
sw.Write ( "UNABLE TO EXTRACT EXCEPTION FROM '" + t.ToString () +
"'\r\n" );
sw.Write ( "====================================================\r\n" );
return;
}
sw.Write ( "Source: " + ex.Source + "\r\n" );
sw.Write ( "Message: " + ex.Message + "\r\n" );
sw.Write ( "TargetSite: " + ex.TargetSite + "\r\n" );
sw.Write ( "Stacktrace: " + ex.StackTrace + "\r\n" );
sw.Write ( "====================================================\r\n" );
}
}
}
You would then execute this code before the Application.Run call:
UnhandledExceptionHandler eh = new UnhandledExceptionHandler ();
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler ( eh.OnThreadException );