上面的代碼塊指的是另一個問題+在SO上的答案不包含這裏適用的正確答案!catch是否支持泛型異常?
我有一個用於單元測試的方法。此方法的目的是確保一段代碼(由委託人引用)會拋出特定的異常。如果拋出異常,則單元測試成功。如果沒有引發異常或引發其他類型異常,則單元測試將失敗。
/// <summary>
/// Checks to make sure that the action throws a exception of type TException.
/// </summary>
/// <typeparam name="TException">The type of exception expected.</typeparam>
/// <param name="action">The code to execute which is expected to generate the exception.</param>
public static void Throws<TException>(Action action)
where TException : Exception
{
try
{
action();
}
catch (TException)
{
return;
}
catch (Exception ex)
{
Assert.Fail("Wrong exception was thrown. Exception of type " + ex.GetType() + " was thrown, exception of type " + typeof(TException) + " was expected.");
}
Assert.Fail("No exception was thrown. Exception of type " + typeof(TException) + " was expected.");
}
下一次調用應該會成功,但它失敗:
int result = 0;
Throws<DivideByZeroException>(() => result = result/result);
當TException
型的預期異常被拋出,它總是由第二catch捕獲,而不是由第一擋。爲什麼是這樣?
當然,如果ex
的類型爲TException
,我可以使用workarround一個catch。我只是想知道/理解爲什麼這個代碼編譯但簡單(從不?)的作品。
編輯
在請求中的 「工作」 演示:
using System;
namespace GenericExceptionDemo
{
class Program
{
static void Main(string[] args)
{
int n = 0;
Catch<DivideByZeroException>(() => n = n/n);
}
static public void Catch<TException>(Action action)
where TException: Exception
{
try
{
action();
Console.WriteLine("No exception thrown. !!!Fail!!!");
}
catch (TException)
{
Console.WriteLine("Expected exception thrown. PASS!");
}
catch(Exception ex)
{
Console.WriteLine("An unexpected exception of type " + ex.GetType() + " thrown. !!!FAIL!!!");
}
}
}
}
你使用什麼單元測試框架?大多數已經有'Assert.Throws' ... –
您的代碼適合我...請顯示一個簡短但完整的程序來演示問題。 –
爲什麼要聲明拋出異常類型的異常?當你使用圖形用戶界面時,.Net框架本身會引發你一個System.Drawing.Exception? –