NullReferenceException - Get name of object that is nothing

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • boshank
    New Member
    • Mar 2010
    • 2

    NullReferenceException - Get name of object that is nothing

    I understand the cause of a NullReferenceEx ception but I was wondering if it is possible to determine the name of the object that is Nothing (or Null) and which is causing the exception. It would be very useful to be able to catch an exception of this kind and print the name of the object that is causing the problem.
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    I assume you are getting this while debugging.

    Just look at your Locals and Autos pallet. Which variable has a value of null?

    Or you can hover the cursor over the highlighted line in Visual Studio. Hover it over each object/variable and the hothelp will show you the current value. One of them will be null.

    Comment

    • boshank
      New Member
      • Mar 2010
      • 2

      #3
      I'm not getting it when debugging unfortunately :(
      I am getting it from a log I keep when an exception is thrown. I have tried to recreate the behaviour when debugging but haven't been able to.
      I am looking to add something to the log which will tell me which variable is coming in as Nothing

      Comment

      • tlhintoq
        Recognized Expert Specialist
        • Mar 2008
        • 3532

        #4
        Then the answer is... "It depends"
        If the exception is just bubbling up from one class, to the next, to the next... the details of the exception may or may not be getting lost.

        throw new exception(nullr eferenceexcepti on());

        for example will throw such an exception with no details.

        Where ever you are writing your log entry should be able to get the details from the (object sender) of the call to log writing method.

        I will share the code for my exception handler which works program-wide, but it is in C#. You should be able to translate it without too much difficulty; or at least get some clues to help you out. You probably care most about lines 52-57 where we get the exception details and stack trace.

        This handles exceptions from the application and gives the user a chance to try to continue, or to abort. Either way, an email is sent back to me with the exception details.

        Code:
            internal class ThreadExceptionHandler
            {
                #region Methods
        
                /// 
                /// Handles the thread exception.
                /// 
                public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
                {
                    try
                    {
                        //18jan10 - attempt to automatically ignore
                        // During debug you can uncomment the below to see the messages.
                        // Don't forget to comment it back out before release so the
                        // customer doesn't get popups.
        
                        // Exit the program if the user clicks Abort.
                        DialogResult result = ShowThreadExceptionDialog(
                            e.Exception);
        
                        if (result == DialogResult.Abort) Application.Exit();
                        if (result == DialogResult.Retry)
                        {
                            Environment.Exit(0);
                            Application.Restart();
                        }
                        Program.MyMainLog.AddEntry("Exception: " + e.Exception.ToString());
                    }
                    catch (Exception err)
                    {
                        // Fatal error, terminate program
                        try
                        {
                            MessageBox.Show(err.Message + "\n\n" + err.StackTrace, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        }
                        catch
                        {
                        }
                    }
                    finally
                    {
                        //Environment.Exit(0);
                        //Application.Restart();
                    }
                }
        
                /// 
                /// Creates and displays the error message.
                /// 
                private DialogResult ShowThreadExceptionDialog(Exception ex)
                {
                    string BigerrorMessage =
                        "Unhandled Exception:\n\n" +
                        ex.Message + "\n\n" +
                        ex.GetType() +
                        "\n\nStack Trace:\n" +
                        ex.StackTrace;
        
                    String errorMessage = "An unexpect error has occured.\n\n" +
                                          "You can try to [ignore] this error and keep running (Possibly with unexpected behavior).\n" +
                                          "You can [abort] the application and relaunch it yourself (Safest option).\n" +
                                          "You can attemp to restart the application with the [retry] button.\n\n" + BigerrorMessage;
                    SendEmail(BigerrorMessage);
        
                    return MessageBox.Show(errorMessage,
                        "Application Error",
                        MessageBoxButtons.AbortRetryIgnore,
                        MessageBoxIcon.Stop);
                }
        
                private void SendEmail(string bodytext)
                {
                    // If an exception is thrown, the email me about it
                    // rather than trust the client to do it: Like that will happen.
                    string toaddress = @"me@email.com";
                    string ccaddress = string.empty;
                    string bccaddress = string.Empty;
                    string subject = "Bug: MyApplication";
                    string fromaddress = "bug@email.com";
                    string frompassword = "bugreport";
                    string replyaddress = "DoNotReply@email.com";
                    string TempFilePath = string.Empty;
                    string mailserver = "smtp.email.com";
                    int smtpport = 587;
        
                    {
                        try
                        {
                            MailMessage myMsg = new MailMessage();
                            if (!string.IsNullOrEmpty(toaddress))
                            {
                                myMsg.To.Add(toaddress);
                                if (!string.IsNullOrEmpty(ccaddress)) myMsg.CC.Add(ccaddress);
                                if (!string.IsNullOrEmpty(bccaddress)) myMsg.Bcc.Add(bccaddress);
                                //TODO: Armour plate this method
                                myMsg.From = new MailAddress(fromaddress);
                                if (!string.IsNullOrEmpty(replyaddress)) myMsg.ReplyTo = new MailAddress(replyaddress);
                                myMsg.Subject = subject;
                                myMsg.Body = bodytext;
                                if (System.IO.File.Exists(TempFilePath))
                                {
                                    myMsg.Attachments.Add(new Attachment(TempFilePath));
        
                                    SmtpClient myMailClient = new SmtpClient(mailserver, smtpport);
                                    myMailClient.Credentials = new System.Net.NetworkCredential(fromaddress, frompassword);
                                    myMailClient.EnableSsl = false;
                                    if (!String.IsNullOrEmpty(toaddress)) myMailClient.Send(myMsg);
                                    Console.WriteLine("Mail sent");
                                    //RaiseLog("Send Email: " + toaddress);
                                }
                                else Console.WriteLine("No attach");
                            }
                        }
                        catch (Exception err)
                        {
                            //MessageBox.Show(err.Message);
                            //RaiseLog(err.Message);
                        }
                    }
                }
        
                #endregion Methods
            }

        Comment

        Working...