Handling Object Null Reference Errors

R

robin9876

Instead of .Net showing an Object reference not set to an instance of
an object error message. Is their a method of handling these messages
and displaying a more user friendly message and recording this
information for further investigation?
 
M

Mark Rae

Instead of .Net showing an Object reference not set to an instance of
an object error message. Is their a method of handling these messages
and displaying a more user friendly message and recording this
information for further investigation?

if (MyObject == null)
{
// do something
}
 
A

Aidy

You could also look into custom error pages to catch all your unexpected
errors and log them to a database while showing a friendly message.

However you should also do what Mark alluded to, and try and write more
robust code. Never assume a method is going to return an object, always
check that it does.
 
S

sloan

Not really.

As others have already said:

Write better/more robust code.


Employee e = Something.GetEmployee();
if(null!=e)
{
//do something with e
}

OR

Employee e = Something.GetEmployee();
if(null==e)
{
throw new ArgumentException ("Employee was expected to be found, but was
not");
}

ArgumentException can/should be replaced with your own custom exception,
like
EmployeeNotFoundException : ApplicationException

...

The better you code, the better your debugging time and maintenance efforts
will be.

...

I just had this happen at work.
I had coded up some xpath/xml code.

I was told "yeah, the xyz attribute will always be there".

I coded to search for the attribute (and its value).
However, I coded it to throw an exception if this attribute was NOT found.

2 days later.
"Your code is blowing up"
"Oh really?"

I check the code, and its working perfectly.
I was like "You said it would always have the xyz attribute".
"It does have the xyz attribute.

We check the Xml.

He had
Xyz in the xml.
Xml is case sensitive.

"Oh , I didn't know xml was case sensitive".

So it was a quick fix. Mainly because I had anticipated the situation, and
wrote the code to handle (or throw an exception) if something was wrong.

It didn't take hours of debugging because I got some "object was null"
exception.

Better code always means faster debugging and maintenance times.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top