我有一个应用程序试图在其构造函数中加载一些预期的注册表设置.
如果无法加载这些(基本的,不可违约的)注册表设置,那么从BCL抛出最合适的.NET异常是什么?
例如:
RegistryKey registryKey = Registry.LocalMachine.OpenSubkey("HKLM\Foo\Bar\Baz");
// registryKey might be null!
if (registryKey == null)
{
// What exception to throw?
throw new ???Exception("Could not load settings from HKLM\foo\bar\baz.");
}
Run Code Online (Sandbox Code Playgroud)
bru*_*nde 14
为什么不创建自定义异常?
public class KeyNotFoundException : RegistryException
{
public KeyNotFoundException(string message)
: base(message) { }
}
public class RegistryException : Exception
{
public RegistryException(string message)
: base(message) { }
}
....
if (registryKey == null)
{
throw new KeyNotFoundException("Could not load settings from HKLM\foo\bar\baz.");
}
Run Code Online (Sandbox Code Playgroud)
此外,Exception
您可以继承而不是继承自己ApplicationException
.这取决于您希望应用程序在这种情况下出现的故障类型.
实际上,我不会在这里抛出异常.我将有一个默认值,然后使用该默认值创建密钥.
如果你必须有一个用户定义的值,我会使用ArgumentException(因为这基本上是你缺少的,你的构造函数的一个参数 - 你存储它的地方与你试图生成的异常类型无关) ).
我会使用ArgumentException或ArgumentOutOfRangeException ..
throw new ArgumentException("Could not find registry key: " + theKey);
Run Code Online (Sandbox Code Playgroud)
引用MSDN:
提供给方法的其中一个参数无效时引发的异常.
...
IMO编写适当的异常消息更为重要.