John Lee
John Lee

Reputation: 277

C# conversion error

I get the following error from the code shown below and can not find a way to cast the object properly. Any help greatly appreciated.

The error occurs on the ex = e.ExceptionObject; line.

Cannot implicitly convert type 'object' to 'System.Exception'. An explicit conversion exists (are you missing a cast?) (CS0266) - C:\DocmentMDB\DocumentMDB.ConvertedToC#\ErrorHandler.cs:59,9

public static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
    // handles all unhandled (i.e. no Catch block) exceptions
    // the following code must be placed in Sub Main and the project
    // use Sub Main as startup
    //Dim currentDomain As AppDomain = AppDomain.CurrentDomain
    //AddHandler currentDomain.UnhandledException, AddressOf myExceptionHandler

    Exception ex = null;
    ex = e.ExceptionObject;

    string strErrorMsg = null;
    string strDisplayMsg = null;
    string strPrintMsg = null;
    int intLoc = 0;

    strErrorMsg = "Unhandled Error In : " + strFormName + " - " + ex.TargetSite.Name + Constants.vbCrLf + Constants.vbCrLf + ex.Message;

    strPrintMsg = "Error detected: " + DateAndTime.Now + Constants.vbCrLf + Constants.vbCrLf + strErrorMsg + Constants.vbCrLf + Constants.vbCrLf + ex.StackTrace;

    strDisplayMsg = "Report this error to your System Administrator" + Constants.vbCrLf + Constants.vbCrLf + strErrorMsg + Constants.vbCrLf + Constants.vbCrLf + "Click YES to print this message.";

    if (MessageBox.Show(strDisplayMsg, "Unhandled Program Error", MessageBoxButtons.YesNo) == DialogResult.Yes) {
        // print the error message
        ErrPrint myPrintObject = new ErrPrint(strPrintMsg);
        myPrintObject.Print();
    }
}

Upvotes: 3

Views: 2845

Answers (3)

AakashM
AakashM

Reputation: 63338

For the reasons discussed in this StackOverflow question, UnhandledExceptionEventArgs.ExceptionObject is statically typed as object, not Exception. So if you want to treat it as an Exception, you will have to cast.

Note that as per one of the answers there, it is usually the case that you can safely direct cast (ie, cast with (Exception)).

Upvotes: 0

CassOnMars
CassOnMars

Reputation: 6181

You need to explicitly cast it: (Exception) e.ExceptionObject There may be conditions in which you are expecting a certain kind of exception:

if (e.ExceptionObject is InvalidOperationException)
{
    // ...
}

And so on.

Upvotes: 1

Uwe Keim
Uwe Keim

Reputation: 40736

Exception ex = (Exception)e.ExceptionObject;

Upvotes: 2

Related Questions