c# - 嵌套的 Try/Catch 块
问题描述
我允许用户将数据从 Excel 文件上传到我的数据库,如果其中一个单元格的格式错误,我希望显示友好的错误消息。总共将要上传 20 个左右的单元格,但现在我只尝试两个。我正在尝试的 Excel 上传在 MedicalTotal 字段中有一些随机文本,而应将其格式化为小数。我确认我的代码正在查看正确的字段。以下控制器代码什么都不做。没有任何内容写入数据库,并且重新加载相同的视图。
在监视窗口中,我收到一条消息“Convert.ToDecimal(table[0]) 引发了 System.FormatException 类型的异常”我已经尝试了带有 Exception 和 FormatException 的代码。我对其他捕获错误的方法持开放态度,请记住,我将重复 try/catch 过程大约 20 次。
[Authorize]
[HttpPost]
public ActionResult CreateBenefitSummary(HttpPostedFileBase FileUpload, Guid ResponseId)
{
BenefitsUploadViewModel model = new BenefitsUploadViewModel();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = Server.MapPath("~/Doc/");
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var table = (from a in excelFile.WorksheetRangeNoHeader("B2", "B32", "Benefits Template") select a[0]).ToList();
TempData["ResponseId"] = ResponseId;
try
{
Benefits b = new Benefits();
b.ResponseId = ResponseId;
try
{
b.MedicalTotal = Convert.ToDecimal(table[0]);
}
catch (FormatException)
{
model.ErrorList.Add("Medical Total cell must use Number, Currency, or Accounting format.");
}
b.StdSicknessAccident = Convert.ToDecimal(table[1]);
if (model.ErrorList.Count > 0) {
return View(model);
}
db.benefits.Add(b);
db.SaveChanges();
}
catch (SqlException ex)
{
ViewBag.Message = ex.Message;
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
TempData["ResponseId"] = ResponseId;
return RedirectToAction("CreateBenefitSummary", "Surveys");
}
}
return View();
}
解决方案
您的 convert.ToDecimal 应该使用 Decimal.TryParse 代替,然后在 if 语句后显示错误消息,查看结果是否已解析。使用 try/catch 进行流量控制通常被认为是不好的做法。
就像是:
Decimal decVal;
if (Decimal.TryParse(table[0], out decVal))
{
b.MedicalTotal = decVal;
}
else
{
model.ErrorList.Add("Medical Total cell must use Number, Currency, or Accounting format.");
}
推荐阅读
- google-sheets - 如何突出显示包含 Google 工作表中特定文本的单元格
- java - 由于文件有空行和标题,代码失败并出现 Nullexecptionerror
- regex - 正则表达式返回找到组 IF 字符串不以'开头 - VSCode - 搜索/替换
- apache-spark - 将数据框的架构保存在 S3 位置
- c# - Microsoft Graph 仅返回前 100 个用户
- sas - 删除 SAS 中 gchart 的轴值
- sql-server - 我想交叉连接两个表,但显示表 NULL 的值之一。我应该使用右外连接吗?
- javascript - 如何推送到尚不存在的数组索引
- mongodb - MongoDB 是否维护副本集中的写入顺序?
- python - pyLDAvis prepare() 很慢