2016-03-28 199 views
0

是否有可能在令牌類的Dispose方法中標記異常?例如:解決Dispose方法中的異常

//code before 
using(var e = new Token()){ 
    //.. 
    throw new Exception(); 
    //.. 
} 
//code after 

我需要的是無效異常並繼續執行代碼。

發生異常並不重要。我知道我可以使用try/catch,但在這種情況下,如果可能的話,我想繞過。

我在通過檢測異常:

bool isExceptionOccurred = Marshal.GetExceptionPointers() != IntPtr.Zero || Marshal.GetExceptionCode() != 0; 
+0

什麼是異常的類型?你可以抓住這個例外,不要做任何事情。 – billybob

+4

「*我知道我可以使用try/catch,但在這種情況下,如果可能的話我想繞過。*」 - 爲什麼?這似乎是一個奇怪的要求或願望。直截了當(也許只有?)的答案將是一個帶有空的「catch」塊的「try」。 –

+1

Try/catch是檢測異常並決定是否處理它們的標準方法。你有什麼理由不使用標準機制進行錯誤處理? –

回答

0

要做到這一點,最好的辦法是使用一個catch塊,因爲這是它的存在了。不要試圖將你的商業需求壓在語言中,用這種語言寫出你需要的東西。

創建一個處理您的「不泄漏異常」要求的抽象層。例如:

public sealed class ExceptionGuard<T>:IDisposable where T:IDisposable 
{ 
    private readonly T instance; 

    public bool ExceptionOccurred { get; private set; } 

    public ExceptionGuard(T instance) { this.instance = instance; } 

    public void Use(Action<T> useInstance) 
    { 
     try 
     { 
      useInstance(instance); 
     } 
     catch(Exception ex) 
     { 
      this.ExceptionOccurred = true; 
      // Hopefully do something with your exception 
     }   
    } 

    public void Dispose() 
    { 
     Dispose(true); 
    } 

    private void Dispose(bool disposing) 
    { 
     if (disposing) 
     { 
      this.instance.Dispose(); 
     } 
    } 
} 

之後,消費和檢查是一件相當簡單的事情。

var guard = new ExceptionGuard(new Token()); 

using (guard) 
{ 
    guard.Use(token => /* Do something with your token */);   
} 

if (guard.ExceptionOccurred) 
{ 
    // React accordingly to this 
} 
相關問題