c# - 如何正确使用 decimal.TryParse 和 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 语句来抛出异常,代码会很快变成意大利面条代码。
你怎么看?还有其他方法吗?
谢谢。
解决方案
正如乔纳森巴克莱所回答的那样,没有什么可以限制您从接球区内投掷。甚至有一种方法可以像这样捕获并重新抛出原始异常:
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
}
推荐阅读
- r - 使用 tbl_summary 获取分类数据的均值
- reactjs - 更新地图内的状态挂钩
- c++ - 使用线程时内存分配问题
- reactjs - 如何使用 next-18next 设置测试环境 next.js 项目?在组件测试中导入 next-18next 的链接时失败
- xslt-2.0 - 如何将“包含”功能与外部列表一起使用
- ios - 尝试构建开源 Signal iOS 应用程序并连接到我自己的服务器
- html - 来自 CSS3 混淆的 @font-face 属性
- r - 用 NA 进行汇总和减法
- dataweave - 使用 Dataweave 将键和值数组压缩到一个对象中
- kubernetes - Error in image_pull_secrets for private repository Airflow deployed in Kubernetes