Get the Null object of a NullReferenceException - c#

I have a problem with a uge solution at work that gets a lot of "Object reference not set to an instance of an object" errors. What's the best way to determine the null object(s) causing the exception?
I can try catch all those exceptions in one place, but can't find a way to determine the member that is null so I can fix it properly.
try {
}
catch (Exception ex)
{
if (ex is ReferenceNullException)
ex.??
}
}
Since I can view the stacktrace it would be reasonable to think you could also get what caused the error.

Think about it for a second. It's a NullReferenceException. That means you're trying to call a method or access a property on a NULL REFERENCE to an object. That means the object reference you're trying to access is EMPTY, null. It does not exist.
So what you're trying to find actually does not exist.
Normally to track down which object reference is null a debugger is used. Just set a breakpoint on the line causing the exception and inspect all variables to see which one is null.
Debugger is your greatest tool.

If you are not able debug NullReferenceException with IDE in case that it only happens at customer side or it is difficult to reproduce, then NullReferenceException.StackTrace which has FUNCTION/FILE/LINE information will help you to locate the null object, NullReferenceException.ToString() also include StackTrace, For example:
System.NullReferenceException: Object reference not set to an instance
of an object.
at WindowsFormsApplication3.Form1.button1_Click(Object sender,
EventArgs e) in
D:\vcs\WindowsFormsApplication3\WindowsFormsApplication3\Form1.cs:line
26
To enable line number for release build, pls check this post Display lines number in Stack Trace for .NET assembly in Release mode

Check out the documentation on Try-Catch http://msdn.microsoft.com/en-us/library/0yd65esw(v=vs.71).aspx
You can have multiple catches in a try catch to handle different exceptions in their own way
try{
//do stuff
} Catch (NullReferenceException ex){
} Catch (Exception ex) {
}

Related

C# catch(FileNotFoundException) and CA1031

So this code triggers CA1031.
try
{
// logic
}
catch (FileNotFoundException) // exception type
{
// handle error
}
While this one does not:
try
{
// logic
}
catch (FileNotFoundException ex) // exception var
{
// handle error
}
Because the exception type is meaningful, I don't need the ex in the first example. But it's not a a general exception type. It's not IOException or Exception. So why does it still trigger the CA1031?
So is there a difference between catch(FileNotFoundException) and catch(FileNotFoundException ex) outside the fact that I don't capture exception info?
So this code triggers CA1031
try
{
// logic
}
catch (FileNotFoundException) // exception type
{
// handle error
}
This occurs because a "general exception such as System.Exception or System.SystemException is caught in a catch statement, or a general catch clause such as catch() is used". To fix it, assign it and handle the error and or rethrow the general exception for it to be handled further up.
Upon further investigation, it seems this used to be an bug, you can see more here; it was a Roslyn issue for FxCop.
To Fix:
Just update the latest FxCop analyzers package and it should go way.
NuGet:
Install-Package Microsoft.CodeAnalysis.FxCopAnalyzers -Version 2.9.7
References:
CA1031
I have two Articles I use as basis for my Exception handling:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
I also link those often when I notice Exception handling errors.
FileNotFound is clearly a exogenous Exception, so it is correct to catch it. However those articles also tell that as a general rule, to always log or expose those Exceptions. Ideally the result of Exception.ToString(). If you do not have a way to reference the caught exception, how could you do either of those two? You can only give a generic error message, but with none of the details you will actually need to debug it.
While there are many cases where you only want to expose the Exception type to the user, there is never one where you only want to log the Exception type. The linked articles mention that explicitly, but due to downvotes and comments it seems nessesary for me to repeat that.
So it is one of those cases where the argument is still going if it is a bug or a feature.
For me it certainly feels more like a feature. I would certainly call you out as potentiall issue, if I saw it in your code. It avoids you under-logging stuff. You could test if the error persist if you write throw; at the end of the catch block. This will re-throw on the exception, so a lack of being able to reference the exception in this ExceptionHandler would not be critical.

how to identify caught errors?

I catch Exception.
I would like to do something if that is a specific error. I can easily identify it with the string.
However I wondered if there is a cleaner way to do this. For example, when I create my own wrapper for exception I add an index.
Is there such a thing in default exception?
The function I use that throws errors is an instantiation of RemoteWebDriver (selenium object). However I don't need an answer specific for that class.
To be more precise, I catch the following error: OpenQA.Selenium.WebDriverException.
However it may be thrown if there is a timeout when creating a driver or if a js file is closed. They have the save HResult.
So I see no way to differentiate them other than to check string unfortunately...
You can catch specific exceptions. For example...
try
{
//Do things with your RemoteWebDriver...
}
catch (ImportantException e)
{
//Do something important with this specific exception
}
catch (Exception e)
{
throw;
}
This code "does" something specific when and only when an Exception of type ImportantException gets thrown, but in all other cases, it does something else (in this example, it just throws the exception).
You can also use exception filters as of C#6. See: https://stackoverflow.com/a/4268291/1672990

.NET exception caught is unexpectedly null

See below for an explanation of what is going on
I have a really weird issue where the exception caught is null.
The code uses MEF and tries hard to report composition errors. Using the debugger I can see the exception being thrown (an InvalidOperationException) but when it is caught by the last catch block in the code below the ex variable is null. This is true both in the debugger and when executing the code normally.
static T ResolveWithErrorHandling<T>() where T : class
{
try
{
IocContainer.Compose(Settings.Default.IocConfiguration);
return IocContainer.Resolve<T>();
}
catch (ReflectionTypeLoadException ex)
{
// ... special error reporting for ReflectionTypeLoadException
}
catch (Exception ex)
{
// ex is null - that should not be possible!
// ... general error reporting for other exception types
}
return null;
}
The code I have replaced with comments is really simple code to format the error message. Nothing strange going on there.
I have tried to alter the code to discover what effect that might have:
If I remove the first catch block (ReflectionTypeLoadException) the exception caught in the final catch block is no longer null.
If I catch another exception type in the first catch block the exception caught in the final catch block is no longer null.
If I add a catch block for InvalidOperationException as the first catch block the exception caught in that block is not null.
If I add a catch block for InvalidOperationException between the two catch blocks the exception caught in that block is null.
The project uses Code Contracts and the code generated by the compiler is post-processed to check the contracts. Unfortunately, I havn't figured out a way to get rid of this for testing purposes without performing major surgery on the project.
My current workaround is to not catch ReflectionTypeLoadException and instead branch on the type of ex in the general exception handler.
What could be the explanation for this "impossible" behavior? What is up with ReflectionTypeLoadException catch block?
Embarrassingly the exception is not null and it cannot be null per the C# standard 15.9.5.
However, using Code Contracts in a project can mess up the display of local variables in the debugger because the IL code generated by the compiler can be rewritten by Code Contracts so the final IL is slightly out of sync with the debug information. In my case the ex variable is displayed as null even it is not. The unfortunate nature of the error reporting taking place right before application termination meant that I believed the error reporting to not be called as a result of ex being null and ex.Message throwing a NullReferenceException inside my catch block. Using the debugger I was able to "verify" that ex was null, except it was actually not null.
My confusion was compounded by the fact that a catch block for ReflectionTypeLoadException seems to affect the debugger display issue.
Thanks to all who responded.
Just ran into this same problem. I finally found out that I catched different exceptions with the same name, like you did:
catch (ReflectionTypeLoadException ex)
{
// ...
}
catch (Exception ex)
{
// ex is not null!
// ...
}
Both are named 'ex'. Changing one of both names solved this problem for me, like:
catch (ReflectionTypeLoadException reflectionEx)
{
// ...
}
catch (Exception ex)
{
// ex is null - that should not be possible!
// ...
}
I ran in the same problem. In my case renaming the exception variable (e.g. ex => ex1) allowed to me to catch any exception...
You should check if at some point, the IocContainer catches an Exception ex throws ex.InnerException without checking if it is null.
C# happily accepts throw null, and ends up in catch (Exception).
I ran into the same problem. The exception was null when viewed in the debugger even though the correct type of exception - UpdateException - was being caught. I could view the exception by opening the Exception Assistant.
As soon as I turned off "Perform Runtime Contract Checking" caught exceptions where no longer null. I have been actively using code contracts for going on a year now and had not seen this problem before I starting working with EF 4.1 in this particular project recently - but I do not know if EF was a controlling variable in regards to caught exceptions being null.
The exception is in fact not null, it's a problem with the debugger.
Code contracts (ccrewrite) changes IL opcodes and that perturbates the debugger, because leave.s opcodes are transformed into leave opcodes.
The two opcodes have different sizes and instruction adresses change, that's why the debugger is lost when exception names are the same.
You can use $exception in the debugger to workaround the issue.
I have got the same situation, too. It happened to be a bug of Eclipse debugger. (Really, this situation can be only the result of some debugger's bug. )
Eclipse restart was enough - runtime exception becomes normal, not null. Other debuggers could be not so kind.

ExecutionEngineException not caught

I am curious why ExecutionEngineException is not caught when I am executing the code below.
try
{
((Window)window).Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
The WriteLine will never be reached. Any ideas how to catch this exception ?
Note: I know the exception is thrown by AvalonDock when one of DockablePanes is in AutoHide mode, is visible and user is trying to close wpf window.
Update:
I've read the remarks section on msdn regarding this exception:
The CLR never throws this exception in such a way that managed code can catch it.
So the question is how to close application nicely after something like that.
The ExecutionEngineException represents a fatal error from which you should not try to recover or handle. You need to tackle this at the source of the problem before it happens and not try to handle it gracefully.
Since you say you already know the source of the problem you should take actions to prevent the application to reach the state where its forced to throw the fatal exception.
Consider adding [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions()] attribute to the method that your code is executed.

Try/Catch block not catching Exception

I have a statement inside a try/catch block, but the exception is not getting caught. Can anyone explain?
Exception Details:
System.NullReferenceException: Object
reference not set to an instance of an
object.
Source Error:
Line 139: try
Line 140: {
Line 141: return (int)Session["SelectedLeadID"];
Line 142: }
Line 143: catch (Exception ex)
Update
This is an ASP.NET application. In the catch block, a new exception is thrown. The code you see is what is displayed on the ASP.NET error page.
That catch block should catch the exception, but make sure there's no re-throwing in there.
Another small comment: I've been tricked quite a few times by VS, cause it breaks on exceptions like that while running in debug-mode. Try to simply press 'continue' or 'F5' and see if your application doesn't work anyway :)
I suspect you're going to need to add more detail - that isn't reproducible just from your code. In particular (as already noted) we'd need to see inside the catch, and verify that the exception is actually being thrown from inside the try and not somewhere else.
Other possibilities:
you have dodgy code inside the exception handler that is itself throwing an exception
you have a dodgy Dispose() that is getting called (using etc)
you are in .NET 1.1 and the thing getting thrown (in code not shown) isn't an Exception, but some other object
If it is only the debugger breaking on the exception and you are using VS2005 or above, you might want to check under Debug->Exceptions... if any of the Common-Language-Runtime-Exceptions are activated. If so, the debugger will always catch the exceptions first, but you are allowed to continue.
To revert to normal execution, simply uncheck the apropriate exceptions from the list.
I also faced this problem
Image
which was solved by removing the tick of
"Break when this exception type is thrown."
Warning:
Of course, I am not aware of the consequences of this.
I've also had such an issue and it was driving me nuts for quite some time, but in the end I figured it out. It's quite stupid, but maybe it might help someone:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter"), "SecondParameter"); //comma placed in the wrong spot
}
catch (Exception ex)
{
//some code
}
}
It should have looked like:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter", "SecondParameter"));
}
catch (Exception ex)
{
//some code
}
}
Since I had many return statements in that function I didn't catch this right away.
Also, the error message I've been receiving wasn't quite what I have expected at first, but now it makes sense:
System.InvalidOperationException: Property
'JsonResult.SerializerSettings' must be an instance of type
'Newtonsoft.Json.JsonSerializerSettings'.
The code looks terribly ugly IMO. For there to be something in the catch() block means you are going to have another return ... statement which AFAIK you should always have a single return statement at the end of each function to make following code easier.
i.e. maybe your code should look like
public int Function()
{
int leadID = 0;
try
{
int leadID = (int)Session["SelectedLeadID"];
}
catch (Exception ex)
{
...
}
return leadID
}
Single exit points are supposed to make the code easier to follow, I guess? Anyway, to get any useful help you have to post more of the function.

Categories