【发布时间】:2015-05-22 22:04:00
【问题描述】:
我遇到了这种情况,不知道如何最好地处理它。输入将不胜感激。想象一下我有这样的方法:
void loaddata()
{
try
{
// EXTRA: I also want to skip below SaveSomething if there was exeption
// last time I called DecryptAndloadXMLdata. This may happen
// if user calls loaddata twice. This is exaclty similar situation
// as app quitting just it happens is user calls loaddata twice
// and during first call there was exception say with DecryptAndloadXMLdata
Savesomething(listOfObjects, xmlPath);//save old data first
xmlPath = newValue;
// some operations
xmlDoc = DecryptAndloadXMLdata(xmlPath);
// some other operations- populate List with data from above XML file
listOfObjects.Add(objectFromXML);
// Here also possibly modify contents of listOfObjects elements
}
catch(Exception ex)
{
xlmPath="";
}
}
现在问题是当应用程序退出时我有这样的功能 自动保存上面填充的 List 对象 方法到文件。喜欢:
void whenAppisQuitting()
{
Savesomething(listOfObjects, xmlPath);
}
但问题是。想象一下xmlDoc = loadXMLdata(); 抛出上述方法。将会发生的是我提到的列表不会被填充,并且当应用程序退出空元素(例如空的listOfObjects)时将被写入xmlPath - 从而损坏我的原始文件,因为有不相关的异常说由于加密loadXMLData 方法。
我希望我已经把我的问题说清楚了。处理这种情况的方法是什么?例如,我所做的你可以看到我在catch 中将xmlPath 设置为空-因此,如果出现任何异常,我认为数据未成功加载-因此现在在应用程序退出时我可以保持冷静,因为不会将任何内容写入文件因为它的xmlPath =""。解决这个问题的方法合理吗?
有点困惑,因为这类问题现在将错误处理提升到不同的级别 - 我需要考虑所有可能的故障类型?
【问题讨论】:
标签: c# exception-handling