constructor.Invoke(parameters) is giving me an error - c#

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
}

Related

How to throw a List<CustomExceptionObj> Exception at once

I have a wcf service, for which I now have made a change to keep compiling my exceptions when they occur into a list, and at the end, throw this list as an Error response. Now single errors is fine. I'm able to throw that and get the output. But throwing the list as an error is proving to be a little challenging.
-What I have tried till now: using AggregateException. I tried sniffing around for a proper implementation. So far, came up with this:
throw new AggregateException("Multiple Errors Occured", ExceptionsList)
Also,
List<CustomExceptionObject> ThrowException(List<CustomExceptionObject> ExceptionList)
{
AggregateException eggExp = new AggregateException(ExceptionList);
throw new eggExp;
}
I keep getting Unhandled Exception error using these method.
Any insight is appreciated.
UPDATE: The error message that I keep getting is -
An exception of type 'System.AggregateException' occurred in XYZ.dll but was not handled in user code.
Keep in mind that throwing a single object of my CustomExceptionObject throws a proper error response in SOAP UI. I can't seem to pull of a list of these exception.
An aggregate exception is the proper way to throw an exception that is a collection of exceptions.
throw new AggregateException("Multiple Errors Occured", ExceptionsList)
You could use this pattern:
public void DoStuff()
{
var ex = new List<Exception>();
try
{
DoSomethingThatThrowsFooException();
DoSomethingElseThatThrowsFooException();
DoSomethingThatThrowsBarException();
}
cath(FooException e)
{
ex.Add(e);
}
if (ex.Count>0)
throw new AggregateException(ex);
}
The BarException will not be caught and not be included in the AggregateException. Ultimately it could lead to an UnhandledException if not caught anywhere else.
So I overcame the issue with a hack. I'm not sure if it is the BEST way. But to get to the desirable outcome that I need, this works just fine.
STEP 1:
Create a class that has a property of List<CustomExceptionObject> type.
STEP 2:
Now when you have to throw an exception, Set this property with the incoming list,
and cast it as a FaultException type, complete with some dummy FaultReason and FaultCode.
throw new FaultException<ListOfExceptionsClass>(listofExceptions, new FaultReason("Here is the List of All exceptions"), Faultcode);
This will give a Fault Object in the response with a neat list of all exceptions occurred.

Can a TargetInvocationException thrown from reflection have a null InnerException

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.

Delegate.DynamicInvoke - catch exception

I'm calling a delegate (dynamically configurable service) using:
public void CallService (Delegate service, IContext ctx)
{
var serviceArgs = CreateServiceArguments(service, ctx);
service.DynamicInvoke(serviceArgs);
}
At this point I want to catch all exceptions that occurred in the called service method, however, I do not want to catch any exception that occurred due to the DynamicInvoke call. E.g.:
service delegate throws DomainException -> catch the exception
DynamicInvoke() throws MemberAccessException because the delegate is a private method -> do not catch the exception, let it bubble up
I hope it is clear what I'm asking. How to decide whether a catched exception originates from the DynamicInvoke call itself or from the underlying delegate.
Oh yeah, and: I cannot use the exception type to decide! It is completely possible that the service itself throws a MemberAccessException as well, because it could do some delegate stuff itself...
Oh yeah, and: I cannot use the exception type to decide! It is completely possible that the service itself throws a MemberAccessException as well, because it could do some delegate stuff itself...
Yes, you can use the exception type to decide. As mentioned in the documentation for Delegate.DynamicInvoke, if the method being called throws an exception (any exception), it will be wrapped in a TargetInvocationException. That is the exception you can catch, and you can then look at its InnerException property to know whether it's an exception you can deal with.

Get values of parameters in stack trace

I am having trouble reproducing a few errors we are seeing in our error log.
It could be made a lot easier if I knew which record ID a specific method was using when it threw an exception.
All of our unhandled exceptions get handled by our global exception handler, which puts all the details of the exception, as well as all the details of the HTTP request, into a log table.
Is there a way to capture the values of all the parameters for the method that threw an exception? Or even better, all the values up the stack trace?
Unfortunately, this is not possible: at the time when you catch the exception in the handler, all the stack frames with the method parameters are gone. Once the control leaves your function, you can no longer access its parameter values.
Since you know the specific function where the crash happens, you could set up an exception handler there to collect all the parameters of interest, and re-throw a wrapped exception. Once the diagnostics is complete, you could revert the code back to normal:
void SuspiciousFunction(string name, long count) {
try {
// The code of your function goes here
} catch (Exception e) {
var args = new Dictionary<string,object> {
{ "name" , name }
, { "count", count }
};
throw new MySpecialException(e, args);
}
}
I would capture the exception in the method it's thrown, gather your parameters and any other needed info, then rethrow the error with a new ApplicationException or other custom Exception that contains your additional info.
From the documentation Environment.StackTrace i would say it is possible.
They say
The stack trace information for each method call is formatted as follows:
"at FullClassName. MethodName (MethodParams) in FileName :line LineNumber "

C# Time of finally execution

Take this code:
using System;
namespace OddThrow
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception("Exception!");
}
finally
{
System.Threading.Thread.Sleep(2500);
Console.Error.WriteLine("I'm dying!");
System.Threading.Thread.Sleep(2500);
}
}
}
}
Which gives me this output:
Unhandled Exception: System.Exception: Exception!
at OddThrow.Program.Main(String[] args) in C:\Documents and Settings\username
\My Documents\Visual Studio 2008\Projects\OddThrow\OddThrow\Program.cs:line 14
I'm dying!
My question is: why does the unhandled exception text occur before the finally's? In my mind, the finally should be excuted as the stack unwinds, before we even know that this exception is unhandled. Note the calls to Sleep() - these occur after the unhandled exception is printed, as if it was doing this following:
Unhandled exception text/message
Finally blocks.
Terminate application
According to the C# standard, §8.9.5, this behaviour is wrong:
In the current function member, each try statement that encloses the throw point is examined. For each statement S, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated:
If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception. The first catch clause that specifies the exception type or a base type of the exception type is considered a match. A general catch clause (§8.10) is considered a match for any exception type. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.
Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.
If an exception handler was not located in the current function member invocation, the function member invocation is terminated. The steps above are then repeated for the caller of the function member with a throw point corresponding to the statement from which the function member was invoked.
If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.
Where am I going wrong? (I've got some custom console error messages, and this is in-the-way. Minor, just annoying, and making me question the language...)
The standard's statements about the order of execution are correct, and not inconsistent with what you are observing. The "Unhandled exception" message is allowed to appear at any point in the process, because it is just a message from the CLR, not actually an exception handler itself. The rules about order of execution only apply to code being executed inside the CLR, not to what the CLR itself does.
What you've actually done is expose an implementation detail, which is that unhandled exceptions are recognised by looking at a stack of which try{} blocks we are inside, rather than by actually exploring all the way to the root. Exceptions may or may not be handled by looking at this stack, but unhandled exceptions are recognised this way.
As you may be aware, if you put a top-level try{}catch{} in your main function, then you will see the behaviour you expect: each function's finally will be executed before checking the next frame up for a matching catch{}.
I could be way off base in the way I'm reading things...but you have a try finally block without a catch.
Juding by the description you posted, since the Exception is never caught, it bubbles up to the caller, works it's way up through the stack, is eventually unhandled, the call terminates, and then the finally block is called.
The output is actually from the default CLR exception handler. Exception Handlers occur before the finally block. After the finally block the CLR terminates because of the unhandled exception (it can't terminate before, as c# guarantees [1] that the finally clause is called).
So I'd say it's just standard behaviour, exception handling occurs before finally.
[1] guranteed during normal operation at least in absence of internal runtime errors or power outage
To add more into the mix, consider this:
using System;
namespace OddThrow
{
class Program
{
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
delegate(object sender, UnhandledExceptionEventArgs e)
{
Console.Out.WriteLine("In AppDomain.UnhandledException");
};
try
{
throw new Exception("Exception!");
}
catch
{
Console.Error.WriteLine("In catch");
throw;
}
finally
{
Console.Error.WriteLine("In finally");
}
}
}
}
Which on my system (Norwegian) shows this:
[C:\..] ConsoleApplication5.exe
In catch
In AppDomain.UnhandledException
Ubehandlet unntak: System.Exception: Exception!
ved OddThrow.Program.Main() i ..\Program.cs:linje 24
In finally
Although not completely expected, the program does behave as it should. A finally block is not expected to be run first, it is only expected to be run always.
I adjusted your sample:
public static void Main()
{
try
{
Console.WriteLine("Before throwing");
throw new Exception("Exception!");
}
finally
{
Console.WriteLine("In finally");
Console.ReadLine();
}
}
In this case you will get the nasty unhandled exception dialog, but afterwards the console will output and wait for input, thus executing the finally, just not before windows itself catches the unhandled exception.
A try/finally without a catch will use the default handler which does exactly what you see. I use it all the time, e.g., in cases where handling the exception would be covering an error but there's still some cleanup you want to do.
Also remember that output to standard error and standard out are buffered.
The try-catch-finally blocks are working exactly as you expected if they are caught at some point. When I wrote a test program for this, and I use various nesting levels, the only case that it behaved in a way that matched what you described was when the exception was completely unhandled by code, and it bubbled out to the operating system.
Each time I ran it, the OS was what created the error message.
So the issue is not with C#, it is with the fact that an error that is unhandled by user code is no longer under the control of the application and therefore the runtime (I believe) cannot force an execution pattern on it.
If you had created a windows form application, and wrote all your messages to a textbox (then immediately flushing them) instead of writing directly to the console, you would not have seen that error message at all, because it was inserted into the error console by the calling application and not by your own code.
EDIT
I'll try to highlight the key part of that. Unhandled exceptions are out of your control, and you cannot determine when their exception handler will be executed. If you catch the exception at some point in your application, then the finally blocks will be executed before the lower-in-the-stack catch block.
To put a couple of answers together, what happens is that as soon as you have a Unhandled Exception a UnhandledExceptionEvent is raised on the AppDomain, then the code continues to execute (i.e. the finally). This is the MSDN Article on the event
Next try:
I believe this case isn't mentioned in the c# standard and I agree it seems to almost contradict it.
I believe the internal reason why this is happening is somewhat like this:
The CLR registers its default exception handler as SEH handler into FS:[0]
when you have more catches in your code, those handlers are added to the SEH chain. Alternatively, only the CLR handler is called during SEH handling and handles the CLR exception chain internally, I don't know which.
In your code when the exception is thrown, only the default handler is in the SEH chain. This handler is called before any stack unrolling begins.
The default exception handler knows that there are no exception handler registered on the stack. Therefore it calls all registered UnhandledException handler first, then prints its error message and marks the AppDomain for unloading.
Only after that stack unrolling even begins and finally blocks are called according the c# standard.
As i see it, the way the CLR handles unhandled exception isn't considered in the c# standard, only the order in which finallys are called during stack unrolling. This order is preserved. After that the "The impact of such termination is implementation-defined." clause takes effect.

Categories