I have this code which Invokes a MethodInfo:
try
{
registrator.Method.Invoke(instance, parameters);
}
catch{
registrator.FailureType = RegistratorFa
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;
}
}
The problem is not in your code anyway.
In the Debug/Exceptions menu, remove all checks.
It should work.