簡體   English   中英

C#正確的異常處理

[英]C# correct exception handling

我目前有一個具有以下示例代碼路徑的應用程序。

    class A
    { 
        private readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(A));
        public void FunctionA()
        {
            try
            {
                B test = new B();
                test.FunctionB();
            }
            catch (Exception ex)
            {
                //handle error ends up here but message is null ref error?
                log.error(ex.Message);
            }
        }
    }
    class B
    {
        private readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(B));
        public void FunctionB()
        {
            try
            {
                //here a custom library function is called that
                //That handles serialized xml data
                //that also has a try catch
            }
            catch (Exception ex)
            {
                //handle error correct error is lost as it falls back to Class A functionA
                log.Error($"Error Encountered During Data operation: {SPID_EX.Message}, \r\n\r\nInner Exception:  {SPID_EX.InnerException.Message}");
            }
        }
    }

問題是我正在嘗試處理functionB catch塊中的錯誤。

但是,如果通過函數B或在函數B執行過程中在調用的庫中引發了異常,則錯誤將在函數A catch塊中結束; 所以我在功能B捕獲中擁有的處理代碼似乎被跳過了,盡管當逐步進入功能B捕獲時到達了log.error ...然后退回到功能A且日志中沒有打印出來自B的消息嗎?

為了處理該功能並繼續執行流程,我在這里缺少什么?

非常感謝

編輯:根據注釋,將以下行添加到FunctionB:

log.Info("Testing123");

輸出:

2018-11-03 01:04:09,361 INFO - Testing123

因此,似乎日志已正確實施。

似乎您的log未初始化,我不確定您使用的是哪個庫,但是您沒有正確實例化log ,並且它很可能為null

根據框架的不同,可能應該對每個類進行DI或靜態更新

似乎問題是這行代碼,我沒有添加到示例中,因為我沒有懷疑它:

log.Error($"Error Encountered During Data operation: {SPID_EX.Message}, \r\n\r\nInner Exception:  {SPID_EX.InnerException.Message}");

看來InnerException.Message是此問題的根本原因,所以最終導致空引用錯誤,然后將其傳遞回functionA。由於先前在內部異常中發現了根本問題,因此我從以前的測試中獲得了此信息。現在至少我從中學到了,也可以為此添加處理程序。

我感謝TheGeneral的幫助,因為它使我更加仔細地了解了實施情況。

感謝所有。

容易^^

try
    {
        //...
    }
    catch(Exception ex)
    {
        //Handle a Exception
        throw new Exception("My Exeception Message");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM