473,512 Members | 15,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NullReferenceException - Get name of object that is nothing

2 New Member
I understand the cause of a NullReferenceException 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.
Mar 4 '10 #1
3 5967
tlhintoq
3,525 Recognized Expert Specialist
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.
Mar 4 '10 #2
boshank
2 New Member
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
Mar 4 '10 #3
tlhintoq
3,525 Recognized Expert Specialist
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(nullreferenceexception());

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.

Expand|Select|Wrap|Line Numbers
  1.     internal class ThreadExceptionHandler
  2.     {
  3.         #region Methods
  4.  
  5.         /// 
  6.         /// Handles the thread exception.
  7.         /// 
  8.         public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
  9.         {
  10.             try
  11.             {
  12.                 //18jan10 - attempt to automatically ignore
  13.                 // During debug you can uncomment the below to see the messages.
  14.                 // Don't forget to comment it back out before release so the
  15.                 // customer doesn't get popups.
  16.  
  17.                 // Exit the program if the user clicks Abort.
  18.                 DialogResult result = ShowThreadExceptionDialog(
  19.                     e.Exception);
  20.  
  21.                 if (result == DialogResult.Abort) Application.Exit();
  22.                 if (result == DialogResult.Retry)
  23.                 {
  24.                     Environment.Exit(0);
  25.                     Application.Restart();
  26.                 }
  27.                 Program.MyMainLog.AddEntry("Exception: " + e.Exception.ToString());
  28.             }
  29.             catch (Exception err)
  30.             {
  31.                 // Fatal error, terminate program
  32.                 try
  33.                 {
  34.                     MessageBox.Show(err.Message + "\n\n" + err.StackTrace, "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  35.                 }
  36.                 catch
  37.                 {
  38.                 }
  39.             }
  40.             finally
  41.             {
  42.                 //Environment.Exit(0);
  43.                 //Application.Restart();
  44.             }
  45.         }
  46.  
  47.         /// 
  48.         /// Creates and displays the error message.
  49.         /// 
  50.         private DialogResult ShowThreadExceptionDialog(Exception ex)
  51.         {
  52.             string BigerrorMessage =
  53.                 "Unhandled Exception:\n\n" +
  54.                 ex.Message + "\n\n" +
  55.                 ex.GetType() +
  56.                 "\n\nStack Trace:\n" +
  57.                 ex.StackTrace;
  58.  
  59.             String errorMessage = "An unexpect error has occured.\n\n" +
  60.                                   "You can try to [ignore] this error and keep running (Possibly with unexpected behavior).\n" +
  61.                                   "You can [abort] the application and relaunch it yourself (Safest option).\n" +
  62.                                   "You can attemp to restart the application with the [retry] button.\n\n" + BigerrorMessage;
  63.             SendEmail(BigerrorMessage);
  64.  
  65.             return MessageBox.Show(errorMessage,
  66.                 "Application Error",
  67.                 MessageBoxButtons.AbortRetryIgnore,
  68.                 MessageBoxIcon.Stop);
  69.         }
  70.  
  71.         private void SendEmail(string bodytext)
  72.         {
  73.             // If an exception is thrown, the email me about it
  74.             // rather than trust the client to do it: Like that will happen.
  75.             string toaddress = @"me@email.com";
  76.             string ccaddress = string.empty;
  77.             string bccaddress = string.Empty;
  78.             string subject = "Bug: MyApplication";
  79.             string fromaddress = "bug@email.com";
  80.             string frompassword = "bugreport";
  81.             string replyaddress = "DoNotReply@email.com";
  82.             string TempFilePath = string.Empty;
  83.             string mailserver = "smtp.email.com";
  84.             int smtpport = 587;
  85.  
  86.             {
  87.                 try
  88.                 {
  89.                     MailMessage myMsg = new MailMessage();
  90.                     if (!string.IsNullOrEmpty(toaddress))
  91.                     {
  92.                         myMsg.To.Add(toaddress);
  93.                         if (!string.IsNullOrEmpty(ccaddress)) myMsg.CC.Add(ccaddress);
  94.                         if (!string.IsNullOrEmpty(bccaddress)) myMsg.Bcc.Add(bccaddress);
  95.                         //TODO: Armour plate this method
  96.                         myMsg.From = new MailAddress(fromaddress);
  97.                         if (!string.IsNullOrEmpty(replyaddress)) myMsg.ReplyTo = new MailAddress(replyaddress);
  98.                         myMsg.Subject = subject;
  99.                         myMsg.Body = bodytext;
  100.                         if (System.IO.File.Exists(TempFilePath))
  101.                         {
  102.                             myMsg.Attachments.Add(new Attachment(TempFilePath));
  103.  
  104.                             SmtpClient myMailClient = new SmtpClient(mailserver, smtpport);
  105.                             myMailClient.Credentials = new System.Net.NetworkCredential(fromaddress, frompassword);
  106.                             myMailClient.EnableSsl = false;
  107.                             if (!String.IsNullOrEmpty(toaddress)) myMailClient.Send(myMsg);
  108.                             Console.WriteLine("Mail sent");
  109.                             //RaiseLog("Send Email: " + toaddress);
  110.                         }
  111.                         else Console.WriteLine("No attach");
  112.                     }
  113.                 }
  114.                 catch (Exception err)
  115.                 {
  116.                     //MessageBox.Show(err.Message);
  117.                     //RaiseLog(err.Message);
  118.                 }
  119.             }
  120.         }
  121.  
  122.         #endregion Methods
  123.     }
  124.  
Mar 4 '10 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

3
9093
by: Terrence | last post by:
I am doing some of the C# walkthroughs to transition from VB to C#. When I try to execute static void Main() { Aplication.Run(new Form1()) } I raise a 'System.NullReferenceException" in...
0
2670
by: monkey king | last post by:
I have a given dll file(PDFCreator.dll) - probably generated by VC++. I want to use its method(PDFCreator()) in dotNet environment. It works well in WindiowsApplication, but bad in WebApplication...
3
9953
by: Mico | last post by:
I would be very grateful for any help with the following problem: I use a DataAdapter to fill a DataSet in the Page_Load method. Later, I use this DataSet to construct a DataTable, then create...
1
4082
by: msnews.microsoft.com | last post by:
I'm trying to fill an array of objects but when I add the first object I get a NullReferenceException. ----------------------------------------------------------------------------...
6
1890
by: Able | last post by:
Dear friends I have some drawing commands in the Form1_paint event. It works pretty well. The drawing gets redrawn when the window is resized. It gets redrawn after I minizie the window and...
0
1006
by: theta | last post by:
Hi everyone, I'm a newbie .NET developer with vb6 experience. I was toying myself with the Howl open source library for Zeroconf networks and I stumbled across an exception I can't quite figure...
0
1167
by: theta | last post by:
Hi everyone. I'm a .NET newbie and I have a problem calling DLL functions from vb .net. I'm trying to access Howl's Rendezvous.dll (www.porchdogsoft.com/products/howl/) from managed code. I was...
6
1492
by: David Whitchurch-Bennett | last post by:
Hi There, I have created a very simple web user control, containing only a combo box. I have created a class which contains some private object variables, for example... Private _anObject as...
7
1965
by: Zytan | last post by:
I just got the strangest error. I have exception code that catches a null reference exception: catch (NullReferenceException ex) { ... } The handling code does nothing but print out data from...
1
17523
by: r035198x | last post by:
This exception occurs often enough in practice to warrant its own article. It is a very silly exception to get because it's one of the easiest exceptions to avoid in programming. Yet we've all got it...
0
7252
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7153
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7432
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7517
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5676
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3230
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1583
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.