473,587 Members | 2,568 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NullReferenceEx ception - Get name of object that is nothing

2 New Member
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.
Mar 4 '10 #1
3 5980
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(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.

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
9125
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 system.windows.forms.dll
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 ,the line that calls the function results in the "Object reference not set to an instance of an object" error. The following is the VB.NET code I...
3
9957
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 a DataRow and search through the DataTable for a specific row. Having found the row, I intend to display the various fields in some text boxes. ...
1
4084
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. ---------------------------------------------------------------------------- ------------------------------------------- Public Class TestClass Public NextSubIndex As Integer = 1 Public arrTestSubClass() As TestSubClass
6
1897
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 bring it back. But when I bring another application to the foreground and drag it across my graphics window or let my window come to foreground...
0
1008
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 out completely. The library is a .dll and i'm using PInvoke (<DllImport>) to declare the functions in the library; I've only declared the following so...
0
1181
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 trying to use <DllImport> Functions for that, but I'm having strange glitches when I try to make it work. I made a module consisting of these:
6
1506
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 Object Public Property anObject() As Object Get
7
1975
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 within the object, ex. So, nothing is changed. And I've found that the exception object, ex, ITSELF is null! So, by accessing it to print its...
1
17534
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 before, lending proof to Einstein's statement: “Only two things are infinite, the universe and human stupidity ...”. Main Cause Dereferencing...
0
7918
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7843
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8206
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8340
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
5392
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2353
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 we have to send another system
0
1185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.