我已經創建了一個方法,如NUnit的Throws
方法。 基本上,如果該方法所採取的操作將導致類型爲T
的異常或任何派生的異常類型(作爲通用參數傳遞),則該方法應該返回true。如何擺脫運行調試器而不是異常捕獲方法之間的不一致行爲
Action a =() => Throw(new DerivedException());
if(!a.Throws<BaseException>())
throw new Exception("catastrophic error");
我有一個幫助器Throw
方法,只是拋出一個給定類型的異常。
DerivedException
類從BaseException
類派生,而類派生自Exception
類。
問題在於Throws
方法的行爲因調試器是否連接而異。如果調試器沒有連接,該方法做我期望它做的事情。當調試器被連接時,它不會將DerivedException
作爲BaseException
捕獲,而是將其捕獲爲Exception
。
下面的代碼複製(可在控制檯應用程序項目文件去。):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Action a =() => Throw(new DerivedException());
if (!a.Throws<BaseException>())
throw new Exception("catastrophic error.");
else
Console.WriteLine("wow, you must not have been debugging.");
}
private static void Throw<T>(T exc) where T : Exception
{
throw exc;
}
}
public static partial class ExtensionMethods
{
public static bool Throws<T>(this Action action) where T : Exception
{
try
{
action.Invoke();
}
catch (T)
{
return true;
}
catch (Exception e)
{
Console.WriteLine(e.GetType());
return false;
}
return false;
}
}
public class BaseException : Exception
{
}
public class DerivedException : BaseException
{
}
}
按F5鍵(調試),並沒有適當地捕捉DerivedException
。 按Ctrl + F5(不調試),它工作正常,作爲BaseException
捕獲DerivedException
。
有人可以解釋這種差異嗎?謝謝。
UPDATE 我正在運行VS 2008專業版,帶有.NET Framework 3.5版SP1。顯然這對於後續版本不是問題。感謝所有試過這個的人。
您沒有使用[Assert.Throws]的任何原因(http://www.nunit.org/index.php?p=exceptionAsserts&r=2.5.10)? – TrueWill
「輸出」窗口中的「第一次機會」消息是什麼意思? –
@TrueWill:我使用的是舊版本的NUnit,有時我喜歡自己做事情。你看到有什麼問題嗎? – user420667