2014-12-04 48 views
0

爲什麼基類的try-catch不捕獲派生類拋出的異常? 我錯過了什麼嗎?無法捕獲派生類拋出的異常

基類:

public class UmBase 
{ 
    protected Thread ThisThread; 

    protected UmBase(int cycleMs, UpdateManager updateManager, 
        string loggerFilename, string loggerFolder = "UpdateManager") 
    { 
    } 

    public void Start() 
    { 
     ThisThread = new Thread(Work); 
     ThisThread.Start(); 
    } 

    public virtual void Iteration() 
    { 
     throw new Exception("Iteration Method should be overidden!"); 
    } 

    public void Work() 
    { 
     while (IsProcessing) 
     { 
      try 
      { 
       Iteration(); 
      } 
      catch (Exception exception) 
      { 
       Log.Error(exception.Message); //WANT TO HANDLE IT HERE 
      } 
      finally 
      { 
       Sleep(100); 
      } 
     }; 
    } 
} 

派生類:

public class ReadParams : UmBase 
{ 
    public ReadParams(UpdateManager updateManager, int cycleMs = 60000) 
     : base(cycleMs, updateManager, "sss") 
    { 
     Iteration(); 
    } 

    public override void Iteration() 
    { 
     try 
     { 
      DbParams.Set(); //EXCEPTION IS THROWN INSIDE 
     } 
     catch (Exception exception) 
     { 
      throw new Exception("Oops!", exception); 
     } 
    } 
} 

我在這裏Can we catch exception from child class method in base class in C#?閱讀並不能找到我的錯誤。

+0

可能的重複[如何從C#派生類中的構造函數捕獲異常?](http://stackoverflow.com/questions/17266105/how-to-catch-exception-from-a-constructor-in -a衍生的類與 - c)中 – Brian 2014-12-04 22:50:12

回答

3

Try/Catch將只捕獲try塊中拋出的異常。這包括try塊中調用的其他方法拋出的任何異常。你有異常配置打破只是未處理拋出See here for how to configure exception breaks

另一種可能性是您的異常在構造對象時拋出,因爲您的ReadParams構造函數在沒有try/catch的情況下調用Iteration()。

public class ReadParams : UmBase 
{ 
    public ReadParams(UpdateManager updateManager, int cycleMs = 60000) 
     : base(cycleMs, updateManager, "sss") 
    { 
     Iteration(); 
    } 

    public override void Iteration() 
    { 
     try 
     { 
      // If throw here (A) 
      DbParams.Set(); //EXCEPTION IS THROWN INSIDE 
     } 
     catch (Exception exception) 
     { 
      // I'll catch here (A) and then throw a new exception 
      throw new Exception("Oops!", exception); 
     } 
    } 
} 

public void Work() 
{ 
    while (IsProcessing) 
    { 
     try 
     { 
      // Exceptions thrown here including the one you 
      // threw in the method Iteration (B) 
      Iteration(); 
     } 
     catch (Exception exception) 
     { 
      // Will be caught here (B) 
      Log.Error(exception.Message); //WANT TO HANDLE IT HERE 
     } 
     finally 
     { 
      Sleep(100); 
     } 
    }; 
} 
0

當你override一個方法,你實際上取代整個方法批發,就派生類的實例而言。

除非您從覆蓋的方法明確調用繼承的方法,否則它不是派生類邏輯的一部分。

2

如果我看它的權利,該序列是:

  1. ReadParams CTOR
  2. UmBase構造函數
  3. ReadParams迭代
  4. ReadParams迭代throw new Exception("Oops!", exception);
  5. 崩潰......因爲ReadParams中沒有try-catch ctor
-1

我面臨同樣的問題。我注意到一件事但不知道原因。 當你私下繼承一個基類時,它的catch塊不會捕獲派生類的異常。 公開繼承基類並試一試。