【发布时间】:2013-09-04 19:28:32
【问题描述】:
当尝试查找不存在的注册表项时,会引发未处理的异常。
看起来当 checkKey 返回 null 并且它试图继续 .GetValue 它抛出异常。
public static string getDirectory(string path, string subpath)
{
if (checkKey(path).GetValue(subpath) != null)
{
return checkKey(path).GetValue(subpath).ToString();
}
else
{
return null;
}
}
我试过 if (checkKey(path) != null & checkKey(path).GetValue(subpath) != null) 但这并没有解决问题。
public static RegistryKey checkKey(string key)
{
if (getBaseCurrent64().OpenSubKey(key) != null)
{
return getBaseCurrent64().OpenSubKey(key);
}
else if (getBaseLocal64().OpenSubKey(key) != null)
{
return getBaseLocal64().OpenSubKey(key);
}
return null;
}
try catch 可以解决这个问题,但我觉得我做错了。
亲切的问候,
【问题讨论】:
-
一般来说:一个方法不要调用两次。调用一次,将返回值放入变量中,然后决定如何处理它。
-
if (checkKey(path) != null && checkKey(path).GetValue(subpath) != null),只有一个&,第二部分仍然会执行,这会引发错误。&&“短路”,意思是如果第一个不是真的,第二个甚至不会被检查。
标签: c# exception error-handling