4

我有一些读取 10 个注册表项的代码,有时值不存在,有时键不存在,有时值不是布尔值等等。我应该如何添加错误处理,目前它被放在一个很大的尝试中{} catch{} 但如果我读取的第二个值失败,那么在程序跳转到 catch{} 时不会读取其余值,我可以为每个值添加一个 try{} catch{} 但我猜有更好的方法. 你会怎么处理这个?我在问,因为我经常遇到类似的问题,我自己的解决方案是添加一个 try{} catch{}。

谢谢您的帮助。

4

8 回答 8

2

首先,吞下异常通常是个坏主意——你能不能写一个方法来检查键等是否存在,如果有则返回值?

如果这绝对是不可能的,您可以将代码重构为对单个方法的多次调用,该方法(对于每个方法)执行 try/catch(吞下):

SomeReturnType foo = HackyMethod(first path);
SomeReturnType bar = HackyMethod(sedond path);

SomeReturnType HackyMethod(string path)
{
    try {} catch {} etc
}
于 2008-11-24T23:03:22.600 回答
1
Dictionary<String,String> regKeys = new Dictionary<String,String>()
{
    { "Key1", String.Empty},
    { "Key2", String.Empty},
    { "Key3", String.Empty}
};

for (int i = 0; i < regKeys.Length; i++)
{
   try
   {
       regKeys[i].Value = ReadFromRegistry(regKeys[i].Key);
   }
   catch (Exception ex)
   {
      Console.WriteLine("Unable to read Key: " + regKeys[i].Key 
         + " Exception: " + ex.Message);
   } 
}
于 2008-11-24T23:16:17.787 回答
1

您如何读取注册表值?Registry 类 (Microsoft.Win32.Registry) 允许您读取注册表值并在值/名称对不存在时返回您指定的默认值,如下所示:

object o = Microsoft.Win32.Registry.GetValue(
    @"HKEY_CURRENT_USER\Software\Microsoft\Calc", "layout", "");

这里的最后一个参数是指定的默认值,如果没有找到值名称则返回。我将其设为空白字符串,但您可以将其更改为您喜欢的任何内容。

于 2008-11-24T23:46:55.103 回答
0

@Marc's answer is the best, but if you absolutely must have a single excpetion that contains the collection of registry keys that had errors you should look at using the Data property of the exception. From the MSDN documentation on this property,

Use the System.Collections.IDictionary object returned by the Data property to store and retrieve supplementary information relevant to the exception. The information is in the form of an arbitrary number of user-defined key/value pairs. The key component of each key/value pair is typically an identifying string, whereas the value component of the pair can be any type of object.

于 2008-11-25T00:11:19.670 回答
0

将读取值的代码重构到它自己的函数中,该函数以您希望的方式处理错误。

于 2008-11-24T23:03:04.443 回答
0

本质上,是的,您想定义每个单独元素的错误处理,而不是定义元素集的错误处理。也就是说,如果您希望捕获每个错误但不导致进程中止,您应该对每个单独的元素执行错误处理,而不是对整个组执行错误处理。

于 2008-11-24T23:04:00.680 回答
0

这取决于错误的严重程度。如果它查找的某些键丢失或类型错误,程序继续运行是否有意义和有用?某些键是否比其他键更重要?

我建议如下:

  • 找到您必须拥有的所有键,并将它们放在一个 try{} 中,使用 catch{} 报告致命错误并启动清理。先执行这个块。

  • 找到所有可选键并将它们分别放在各自的 try{} 块中,这样您就可以恢复并继续使用其他键。为了使这更简单,您可以添加一个包装器方法,该方法具有必要的 try/catch 块和错误检查,并将键名作为参数。

于 2008-11-24T23:05:04.907 回答
0

编辑:改变了一切。:PI 建议了一个结构或类(以前),但现在我将其更改为一个简单的字符串集合。

我头顶上的一些伪代码....

public IEnumerable<string> ReadRegistryKeys()
{
    IEnumerable<string> resultList = new List<string>();
    if (string.IsNullOrEmpty(read_in_key_#1())
    {

        resultList.Add("Failed to load key 'blah'..");
    }

    if (.... read in the next key .. etc.... ) ...

    return resultList == null || resultList.Count <= 0 ? null : resultList;
}

如果您愿意,您也可以使用 StringCollection (System.Collections.Specialized?)。

于 2008-11-24T23:06:49.303 回答