在下面的方法中捕獲的異常類型,第一catch塊永遠不會運行,即使當類型ExceptionType的拋出異常:類型參數給出在C#2.0
/// <summary>
/// asserts that running the command given throws an exception.
/// </summary>
public static void Throws<ExceptionType>(ICommand cmd)
where ExceptionType : Exception
{
// Strangely, using 2 catch blocks on the code below makes the first catch block do nothing.
try
{
try
{
cmd.Execute();
}
catch (ExceptionType)
{
return;
}
}
catch (Exception f)
{
throw new AssertionException(cmd.ToString() + " threw an exception of type " + f.GetType() + ". Expected type was " + typeof(ExceptionType).Name + ".");
}
throw new AssertionException(cmd.ToString() + " failed to throw a " + typeof(ExceptionType).Name + ".");
}
通過下述試驗所示:使用
[Test]
public void Test_Throws_CatchesSpecifiedException()
{
AssertThat.Throws<AssertionException>(
new FailureCommand()
);
}
下面的類:
class FailureCommand : ICommand
{
public object Execute()
{
Assert.Fail();
return null; // never reached.
}
public override string ToString()
{
return "FailureCommand";
}
}
給出的N以下輸出單位:
TestUtil.Tests.AssertThatTests.Test_Throws_CatchesSpecifiedException: FailureCommand引發了NUnit.Framework.AssertionException類型的異常。預期的類型是AssertionException。
我也嘗試使用1個try塊的2個catch塊(而不是在外部嘗試中嵌套try/catch),但得到了相同的結果。
關於如何捕獲在一個catch塊中作爲類型參數指定的異常,但在另一個catch塊中捕獲所有其他異常的任何想法?