c# - 处理加载和显示数据之间的异常

标签 c# exception

我遇到过这种情况,不确定如何最好地处理它。输入将不胜感激。想象一下我有这样的方法:

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/

相关文章:

c++ - 无法捕获 std::thread 构造函数抛出的异常

java - 了解 Mockito 验证背后的语义

c++ - 使用异常中止一系列用户输入 - 好吗?坏的?

异常跟踪解决方案

c# - Android 和 PC 之间的通信 (C#)

c# - 从代码文件动态设置控件的属性

c# - 在没有 SQL View 的情况下,将数据反规范化为代码优先 Entity Framework 实体

java - 由 : java. lang.NoClassDefFoundError : when class exists under tomcat/lib? 引起

c# - 在html中的C#标签中使用变量,使用asp.net

c# - 如何在类级别从 PropertyInfo 获取 DataContract 属性?