我遇到过这种情况,不确定如何最好地处理它。输入将不胜感激。想象一下我有这样的方法:
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="";
}
}
现在的问题是当应用程序退出时我有这样的功能 自动保存上面填充的列表对象 方法到一个文件。喜欢:
void whenAppisQuitting()
{
Savesomething(listOfObjects, xmlPath);
}
但问题是。想象 xmlDoc = loadXMLdata();
抛出上述方法。将会发生的是我提到的列表不会被填充,当应用程序退出空元素(例如空 listOfObjects
)时,将被写入 xmlPath
- 从而损坏我的原始文件因为 loadXMLData
方法中的加密导致不相关的异常说。
我希望我已经把我的问题说清楚了。处理此类情况的方法是什么?例如我所做的,你可以看到我在 catch
中将 xmlPath
设置为空 - 因此如果出现任何异常,我认为数据未成功加载 - 因此现在在应用程序退出时我可以很平静,因为它的 xmlPath =""
不会将任何内容写入文件。解决这个问题的方法是否合理?
有点困惑,因为这种问题现在将错误处理提高到不同的级别 - 我需要考虑所有可能的故障类型?
最佳答案
What is the way to deal with such situations?
我会设置一个标志,指示解析时出现错误。将路径设置为 string.Empty
会导致混淆(IMO)。也许空字符串可能是传递给您的方法的可能值。
catch(Exception ex)
{
// Log
IsParsingSuccessful = false;
}
当你想写的时候看看那个标志:
void AppIsQuitting()
{
if (IsParsingSuccessful)
{
SaveSomething(listOfObjects, xmlPath);
}
}
关于c# - 处理加载和显示数据之间的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406511/