我知道这个问题经常被问到,但我似乎找不到令我满意的答案。我想从一开始就学习这个“正确的”。
string [] list = {"foo", "bar", "foo"};
for(int i = 0; i<list.Length;i++)
{
try
{
//begin sql transaction
if(!list[i].Equals("foo"))
throw new Exception("foo exception");
else
{
//save stuff into DB
Console.WriteLine(list[i]);
//commit transaction here
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
//rollback transaction here
}
Console.WriteLine("Next record");
}
我已经在下面的 fiddle https://dotnetfiddle.net/0nftFD 中测试了代码现在我的问题是:
如果我要在类似于上面示例的 for 循环中处理文件,并且其中一个文件有 IO 异常,我会记录它,通过电子邮件发送给管理员等,然后继续处理下一个文件。
据我所知,它会像这样工作,这是好还是坏的做法?我想立即正确地学习这个:)
编辑:因为我之前没有提到这一点,所以我也会得到特定的异常(exception)情况。
我之前没看到的资源:
最佳答案
根据要求,您可以将数据处理和错误处理分开:
- 迭代文件
- 如果发生异常,将足够的信息捕获到列表、字典中以便稍后处理
- 循环遍历所有对象后,循环遍历错误
例如:
string[] list = {"foo", "bar", "foo"};
var errors = new Dictionary<string, ExceptionDispatchInfo>();
for(int i = 0; i < list.Length; i++)
{
try
{
if(!list[i].Equals("foo"))
throw new Exception("foo exception");
else
Console.WriteLine(list[i]);
}
catch(Exception ex)
{
var edi = ExceptionDispatchInfo.Capture(ex);
errors.Add($"{list[i]}_{i}", edi);
}
Console.WriteLine("Next record");
}
foreach(var error in errors)
{
//Process error and throw the original exception if needed
//error.Value.Throw();
}
关于c# - 捕获异常后继续程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62671553/