Whilst browsing the source code for System.ComponentModel.DataAnnotations.CustomValidationAttribute here, I saw the following code (shortened):
try
{
methodInfo.Invoke(null, methodParams);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException != null)
{
throw ex.InnerException
}
throw;
}
Here, the code checks if ex.InnerException is null.
I didn't think that a TargetInvocationException could ever have a null InnerException if it was thrown from reflection invocation.
Is this possible? If so, please provide a scenario where the InnerException can be null.
The MSDN states that
When created, the TargetInvocationException is passed a reference to the exception thrown by the method invoked through reflection. The InnerException property holds the underlying exception.
So theoretically using only framework reflection methods it should never be null... theoretically :P
Of course it can (and will!) be null if you explicitly threw it from the method that was being invoked.
Related
I'm trying to invoke an instance using constructor.Invoke and also passing some parameters in it, but I'm getting
System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
Any inputs would be helpful
Thanks
TargetInvocationException basically means that the member could be invoked successfully and the exception occurred in the invoked member itself. To differentiate it from other issues (eg. wrong instance, invalid number or type of parameters, etc.) the exception thrown by the invoked member is wrapped into a TargetInvocationException. Just look at its InnerException to see what happened.
If you want to 'unwrap' such exceptions as if you called the constructor without reflection you can do something like this:
try
{
return myConstructorInfo.Invoke(parameters);
}
catch (TargetInvocationException e)
{
// we could just throw e.InnerException but that would corrupt the
// original stack trace, showing this line as the source of the exception
ExceptionDispatchInfo.Capture(e.InnerException).Throw();
throw; // unreachable, just to satisfy the compiler if there is no return later
}
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) {
}
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.
I have a class with a method and I want to throw an exception within the method. In this I would like to reference the method and class in which the exception was thrown to find the source of the error more easily.
public class SomeClass
{
public void SomeMethod()
{
(..)
Throw new Exception("An error occurred. Method:" + ?? + ", Class:" + ?? +");
}
You dont need to do that. Look at the StackTrace property of the exception in your try-catch block.
That information will already be in the stack trace. There's no need to include it in the message as well.
If you absolutely have to, there's MethodBase.GetCurrentMethod(). For the class, would you want the class of the execution-time object on which the method was called, or the method which is actually executing? (I would stick to the stack trace though...)
You actually already have all that information and just need to access it via the Exception's StackTrace property with something like:
try
{
// to do something exceptional
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
This sample just write to std out but you could do anything with the StackTrace information you want, including logging it to file or db.
You can actually use the StackTrace class for that.
I am learnig CSharp.I have some doubts in handling exceptions.Kindly guide me to improve my
coding knowledge.
Suppose i construct a code segment :
try {
SomeWork();
return success;
}
catch (someException ex)
{
throw new ExceptionDetails(ex);
return failure;
}
catch(AnotherException exp)
{
throw new ExceptionDetails(exp);
return failure;
}
finally
{
CleanUpStuff();
}
Questions:
(1) Can i use return statement after "throw" (throwing exception) ?
(2) Is throwing an exception ugly practice?.When exactly do i need to throw an exception?Do i need to use "throw" to report only custom exception ?
(3)
try
{
SomeWork();
}
catch(StringIndexOutOfBound ex)
{
throw;
}
using anonymous throw statement inside catch is a good practice?
1) A thrown exception (if not handled) will automatically return to the previous method so there is no need to return. In fact, the compiler should warn you that there is unreachable code.
2) Throwing exceptions is not ugly as long as you do it for ... exceptional circumstances. Your coding should be defensive enough that you don't rely on exceptions for normal program flow.
3) Don't do #3 if you're not going to be doing anything else with the exception. If you are going to be logging it or doing something meaningful and would still like to rethrow the exception, then use it "anonymously" (??) as you have there.
Hint: anything after throw will never be executed. Compiler should tell you that!
In regards to 3- read about the differences between throw and throw ex. As Daniel says the compiler will tell you about unreachable code.
1) Having a return statement after a thrown Exception will not compile and you should get an Unreachable code warning.
2) Throwing an exception is perfectly valid, this potentially allows for some more generic error handling to occur. e.g.
public void readFile()
{
try
{
// Perform IO action
}
catch ( FileNotFoundException ex )
{
// Perform error recovery e.g. create a default file
}
catch ( Exception ex )
{
// Cant perform any error recovery at this level so throw the exception to allow the calling code to deal with it
throw;
}
}
You could argue here that you should be testing to see if the File exists before perforrming the IO action. As a rule of thumb if you can test for something with an if statement, then you should do so. You can generally catch specific exceptions when you know you can recover from them within the scope that they are generated.
This sort of question really depends on the situation as testing before carring out an action could be a better course of action. You will get more of a feel for what is required with practice!
3) As has been mentioned elsewhere in the post, it is generally a good idea not to just 'throw' an exception as having information about how and where it occurred is often very useful in debugging.
Whan you throw an exception your return statement won't work.
Try to catch the specific exception and handle it from there itself and also return the value after the finally block.
throw ex
will reset the stack trace to the point of the throw.
throw
will maintain the original stack which will be helpful when debugging.