Uncatcheable exception from MethodInfo.Invoke
I have this code which Invokes a MethodInfo:
try
{
registrator.Method.Invoke(instance, parameters);
}
catch{
registrator.FailureType = RegistratorFailureType.ExceptionInRegistrator;
//registrator.开发者_C百科Exception = e;
}
The Registrator is just a MethodInfo wrapper, the Method property is the MethodInfo object itself. parameters is and object[] and instance is a correct instance of the Method's declaring type (created with Activator.Create).
The Method looks like this (I was testing exception catching):
class Test : Plugin, ITest
{
public void Register(IWindow window)
{
throw new Exception("Hooah");
}
}
The problem is: The exception is never caught and the Visual Studio's uncaught exception bubble pops up.
This is in VS 2010 with .NET 4.0
The problem is not in your code anyway.
In the Debug/Exceptions menu, remove all checks.
It should work.
Have you tried this?
In Program.cs
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
And a try/catch on the Run method:
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
}
The problem is not with the code you're showing.
I tried this:
void Main()
{
Test instance = new Test();
object[] parameters = new object[] { null };
MethodInfo method = typeof(Test).GetMethod("Register");
try
{
method.Invoke(instance, parameters);
}
catch
{
Console.Out.WriteLine("Exception");
}
}
interface ITest { }
interface IWindow { }
class Plugin { }
class Test : Plugin, ITest
{
public void Register(IWindow window)
{
throw new Exception("Hooah");
}
}
It printed "Exception" as expected. You need to show us more code.
If I modify the code like this:
catch(Exception ex)
{
Console.Out.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
Then I get a TargetInvocationException, where the InnerException property is your thrown Exception.
I think the problem is that you are expecting a specific exception type, maybe IOException
or something, but actually MethodInfo.Invoke()
will throw a TargetInvocationException
:
try
{
registrator.Method.Invoke(instance, parameters);
}
catch (TargetInvocationException tie)
{
// replace IOException with the exception type you are expecting
if (tie.InnerException is IOException)
{
registrator.FailureType = RegistratorFailureType.ExceptionInRegistrator;
registrator.Exception = tie.InnerException;
}
else
{
// decide what you want to do with all other exceptions — maybe rethrow?
throw;
// or maybe unwrap and then throw?
throw tie.InnerException;
}
}
精彩评论