【发布时间】:2014-08-25 15:36:10
【问题描述】:
我正在编写一个保存和加载系统,将游戏对象保存为 JSON 兼容格式并重新加载它们。保存对象很好,而且相当简单。但是,我正在尝试使加载过程更加安全,并且更容易查明错误。显然,当我从 JSON 文件加载数据时,所有内容都是从字符串转换的,可能会出现各种用户错误。
每个对象加载方法都包含类似的东西---
public void Load()
{
try
{
// Deserialize..
// Potential for all kinds of exceptions, invalid casts, missing info, etc..
// For eg:
bool active = data.GetField("active").Value<bool>();
// GetField() throws an exception if the field doesn't exist.
// Value<T>() throws an exception if it's an invalid cast, etc.
}
catch(Exception e)
{
// ..and those exceptions get caught and logged here.
Logger.LogError(e.ToString, this);
}
}
在对象 Load 方法中捕获所有异常的好处之一是,当使用对象作为参数调用“LogError()”时,它将突出显示 IDE 层次结构中引发错误的违规对象(无论是哪一个)都可以非常快速地找到有错误的对象并调试它的脚本或保存的数据。
这是引发和捕获异常的适当用法,还是我应该实施更好的设计模式?
感谢您的宝贵时间, 山姆
【问题讨论】:
标签: c# exception logging load try-catch