locked
Exception type for a generic method RRS feed

  • Question

  • Given a generic method without parameters, if the type parameter itself is not valid, what would be the right exception to throw?
    public T Value<T>()
        where T : class
    {
        // ...
    
        throw new ArgumentException("Only ThisType or ThatType supported.");
    }
    Maybe InvalidOperationException is better here as there is not parameter to associate to the ArgumentException?
    Saturday, May 13, 2017 1:52 AM

Answers

  • I don't think that ArgumentException is the ideal one, since this refers to the arguments passed to the method (none in this case), and not to the generic Type argument. As you mentioned, maybe InvalidOperationException would be better.

    You can also use a restriction on the method: where T: ParentClassOrInterface

    Presuming that there is something in common to all the T's that you are going to pass, making them all inherit from a given class, or implement a given interface would be a solution. In this way, a wrong T would produce a compile-time error, and you wouldn´t need to throw an exception at runtime.

    • Marked as answer by Ritmo2k Saturday, May 13, 2017 12:22 PM
    Saturday, May 13, 2017 11:24 AM

All replies

  • I don't think that ArgumentException is the ideal one, since this refers to the arguments passed to the method (none in this case), and not to the generic Type argument. As you mentioned, maybe InvalidOperationException would be better.

    You can also use a restriction on the method: where T: ParentClassOrInterface

    Presuming that there is something in common to all the T's that you are going to pass, making them all inherit from a given class, or implement a given interface would be a solution. In this way, a wrong T would produce a compile-time error, and you wouldn´t need to throw an exception at runtime.

    • Marked as answer by Ritmo2k Saturday, May 13, 2017 12:22 PM
    Saturday, May 13, 2017 11:24 AM
  • In this case the two supported types are string and byte[]. Do you see a way to improve the signature such that callers get the friendly syntax of instance.Value<string>() or instance.Value<byte[]>() in a more streamlined way?

    Thanks.

    Saturday, May 13, 2017 11:53 AM
  • The only thing that comes to mind is to create two separate methods, ValueString() and ValueByteAray(). These two methods can be made public, and both of them could in turn call Value<T>, which would be private so that it can't be called from outside the class using a non-expected T. Then, the type of exception that it throws in case of a wrong T doesn't matter much, since it should not be seen by the external callers of the class.
    Saturday, May 13, 2017 12:18 PM