Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most appropriate .NET exception to throw upon failing to load an expected registry setting?

Tags:

c#

.net

I have an application which tries to load some expected registry settings within its constructor.

What is the most appropriate .NET Exception from the BCL to throw if these (essential, non-defaultable) registry settings cannot be loaded?

For example:

 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.");
 }
like image 357
Daniel Fortunov Avatar asked Dec 15 '08 16:12

Daniel Fortunov


4 Answers

Why not create your custom exception?

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.");
}

Also, instead of inheriting from Exception you could inherit from ApplicationException. This depends on the kind of failure you want your application to have in this situation.

like image 101
bruno conde Avatar answered Oct 19 '22 23:10

bruno conde


actually, I wouldn't throw an exception here. I would have a default value, and then create the key using that default value.

If you MUST have a user-defined value, I'd use the ArgumentException (as that's fundamentally what you're missing, an argument for your constructor--where you store it is irrelevant to the type of exception you're trying to generate).

like image 43
Stephen Wrighton Avatar answered Oct 20 '22 00:10

Stephen Wrighton


I'd go with ArgumentException or ArgumentOutOfRangeException..

throw new ArgumentException("Could not find registry key: " + theKey);

Quoting MSDN:

The exception that is thrown when one of the arguments provided to a method is not valid.

...

IMO writing a proper exception message is more important.

like image 26
chakrit Avatar answered Oct 20 '22 01:10

chakrit


It depends on why it failed. If it's a permissions issue, the I'd go with System.UnauthorizedAccess exception:

The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

I don't know if it matches the "specific type", but it is a security error, and access wasn't authorized.

On the other hand, if the item just doesn't exist then I'd thrown a FileNotFound exception. Of course, a registry key isn't a file, but FileNotFound is pretty well understood.

like image 43
Joel Coehoorn Avatar answered Oct 20 '22 01:10

Joel Coehoorn