2009-11-18 28 views
2

在下面的方法中捕獲的異常類型,第一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塊中捕獲所有其他異常的任何想法?

回答

3

工作正常,我在這個測試:

using System; 
using System.IO; 

class Test 
{ 
    static void Main() 
    { 
     Throws<ArgumentNullException>(() => File.OpenText(null)); 
    } 

    public static void Throws<ExceptionType>(Action cmd) 
     where ExceptionType : Exception 
    { 
     try 
     { 
      try 
      { 
       cmd(); 
      } 
      catch (ExceptionType) 
      { 
       Console.WriteLine("Caught!"); 
       return; 
      } 
     } 
     catch (Exception f) 
     { 
      Console.WriteLine("Threw an exception of type " + f.GetType() 
       + ". Expected type was " + typeof(ExceptionType) + "."); 
     } 

     Console.WriteLine("No exception thrown"); 
    } 
} 

你怎麼一定是兩個AssertionException例外是相同的?它們絕對在同一個命名空間中(打印typeof(ExceptionType)而不僅僅是名稱屬性)?他們是否來自同一大會?由於多個測試框架版本共存,我不會感到驚訝......

嘗試使用除AssertionException之外的其他異常來簡化生活。

0

我還沒有調試過這段代碼,或者看了太長時間,但是可能是因爲你第一次「返回」語句導致代碼出現HALT並離開該方法。因此,異常是「被捕獲」或「被處理」(但是你看它),並且外部try/catch塊從未被執行。

你想要這樣做嗎?

try   
{    
    try    
    {     
     cmd.Execute();    
    }    
    catch (ExceptionType)    
    {     
     throw; 
    }   
}   
catch (Exception f)   
{    
    throw new AssertionException(cmd.ToString() + " threw an exception of type " + f.GetType() + ". Expected type was " + typeof(ExceptionType).Name + ".");   
} 
相關問題