簡體   English   中英

如何正確使用decimal.TryParse和decimal.Parse

[英]How to properly use decimal.TryParse and decimal.Parse

我有嘗試將字符串解析為十進制數的方法。 起初我用decimal.Parse 實現了這個方法,並將方法的主體包裝在try catch 塊中。 然后當 Parse 方法拋出 FormatException 時,我在 catch 塊中拋出異常。 我知道在 catch 塊中拋出異常不是一個好習慣,但我不知道如何添加有關解析錯誤的詳細信息。 然后我將方法重構為如下所示:

public List<ExcelGeneralLedgerRow> ParseGeneralLedger(DataTable worksheet)
        {
            var rows = new List<ExcelGeneralLedgerRow>();
            for (int i = 1; i <= worksheet.Rows.Count - 1; i++)
            {
                var row = worksheet.Rows[i];

                if (!decimal.TryParse(row[3].ToString(), out decimal value))
                {
                    throw new Exception($"detailed info about that exception was thrown on specific row.");
                }

                var syntheticAccountNumber = row[0].ToString();
                var analyticAccountNumber = row[1].ToString();

                if (analyticAccountNumber == String.Empty)
                {
                    analyticAccountNumber = "000";
                }

                var text = row[2].ToString();
                rows.Add(new ExcelGeneralLedgerRow(syntheticAccountNumber, analyticAccountNumber, text, value));
            }

            return rows;
        }

這是一個好習慣嗎? 在我看來,通過這種方法,我可以向拋出的異常添加更多信息。 我還可以解析多個值並添加有關哪個解析失敗的信息。 但是如果我實現大量的 if 語句來拋出異常,代碼會很快變成意大利面條式的代碼。

你怎么看? 還有其他方法嗎?

謝謝。

正如 Johnathan Barclay 所回答的那樣,沒有什么可以限制您從接球塊內投擲。 甚至有一種方法可以捕獲並重新拋出原始異常,如下所示:

try {
   // Do something here that throws exception
} catch(Exception ex) {
   // log the exception
   throw;
   // instead of throw ex; which would reset the information of the original exception
}

您的代碼雖然沒有任何問題,但會受益於更具體的異常。 因此,自定義異常

class GeneralLedgerParseException : Exception
{

    // Properties with the additional information
    public string //...

    public GeneralLedgerParseException()
    {

    }
}

通過這種方式,您甚至可以為特定異常創建 catch 子句並處理它們,而無需捕獲其他通用異常。

try {
  //
} 
catch (GeneralLedgerParseException glex) {
  // Any other kind of exception will not be caught here
} 
catch (Exception ex) {
  // All other exceptions will be caught here
}

暫無
暫無

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

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