【发布时间】:2009-11-18 14:10:34
【问题描述】:
在下面的方法中,第一个 catch 块永远不会运行,即使抛出了 ExceptionType 类型的异常:
/// <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";
}
}
在 NUnit 中给出以下输出:
TestUtil.Tests.AssertThatTests.Test_Throws_CatchesSpecifiedException: FailureCommand 引发了 NUnit.Framework.AssertionException 类型的异常。预期的类型是 AssertionException。
我还尝试将 2 个 catch 块用于 1 个 try 块(而不是在外部 try 中嵌套 try/catch),但得到了相同的结果。
关于如何在一个捕获块中捕获指定为类型参数的异常,但在另一个捕获块中捕获所有其他异常的任何想法?
【问题讨论】:
标签: c# .net generics exception