views:

59

answers:

3

I'm developing a C# utility class that runs an external command on a Linux server via SSH (I'm using SharpSSH; I like it so far and I recommend it) and gives back some meaningful information based on the command's output.

Somewhere in the aforementioned output is an integer that should never be outside some range, but I'd like to prevent against that unlikely possibility. What exception is more proper to throw is the received number is actually outside the range? I'm thinking ArgumentOutOfRangeException, but it's not really an argument. Autocomplete doesn't give me any good candidates. Any suggestions?

+2  A: 

The type of exception thrown is only relevant for two reasons:

  1. You (or your consumers) intend to catch the exception in certain cases and somehow respond to it programatically in a catch( ) block.
  2. You want additional clarity for the caller when a particular problem occurs - even it it can't be programmatically responded to.

So, to respond to your question,

  1. if you think that consumers of this code may want to catch that particular exception, and somehow handle it, create a custom exception inheriting from Exception with the necessary detail.
  2. If you don't think that handling or responding to this exception would be useful, consider either ApplicationException or possible InvalidOperationException for the type of error you describe.
LBushkin
There is no reason to inherit from ApplicationException, just inherit from Exception class itself. This is I think even official recommendation from .NET team.
lubos hasko
Quite right ... I amended this.
LBushkin
+1  A: 

I'd suggest InvalidOperationException. Another option is NotSupportedException if perhaps that value goes into potentially used ranges (say in the future).

Ultimately I'd suggest:

namespace YourProtocol
{
    public class UnexpectedProtocolValueException : Exception
    {
sixlettervariables
+1  A: 

You can find a complete list of .NET Exceptions on Mike Vallotton's Blog - this should help you decide. Failing that, you could always create your own custom Exception class.

Dan Diplo