簡體   English   中英

MethodInfo.Invoke的無法捕獲的異常

[英]Uncatcheable exception from MethodInfo.Invoke

我有調用MethodInfo的這段代碼:

try
{
     registrator.Method.Invoke(instance, parameters);
}
catch{
    registrator.FailureType = RegistratorFailureType.ExceptionInRegistrator;
    //registrator.Exception = e;
}

Registrator只是一個MethodInfo包裝器,Method屬性是MethodInfo對象本身。 參數是and object [],instance是方法的聲明類型的正確實例(使用Activator.Create創建)。

該方法如下所示(我正在測試異常捕獲):

class Test : Plugin, ITest
{
    public void Register(IWindow window)
    {
        throw new Exception("Hooah");
    }
}

問題是:永遠不會捕獲到異常,並且會彈出Visual Studio的未捕獲異常氣泡。

這是在帶有.NET 4.0的VS 2010中

無論如何,問題不在您的代碼中。
在“調試/異常”菜單中,刪除所有檢查。
它應該工作。

你有嘗試過嗎?

在Program.cs中

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

並嘗試/抓住Run方法:

try
{
    Application.Run(new Form1());
}
    catch (Exception ex)
{
}

問題不在於顯示的代碼。

我嘗試了這個:

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");
    }
}

它按預期方式打印了“異常”。 您需要向我們展示更多代碼。

如果我這樣修改代碼:

catch(Exception ex)
{
    Console.Out.WriteLine(ex.GetType().Name + ": " + ex.Message);
}

然后,我得到一個TargetInvocationException,其中InnerException屬性是引發的異常。

我認為問題在於您期望使用特定的異常類型,也許是IOException東西,但是實際上MethodInfo.Invoke()會拋出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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM