InBetween
InBetween

Reputation: 32740

Should I throw an exception if using an invalid generic type and if yes, which one?

I am building a simple custom lightweight csv generator class named, oddly enough, CsvWriter<T>.

The way this class works is that it will automatically generate a csv to an underlying Stream from all public properties that are marked with a predefined attribute that we aptly named CsvPropertyAttribute.

Upon object creation I would like to check that the generic type implements at least one public property with the predefined CsvPropertyAttribute. If that weren' the case I'd like to throw an exception as the generic type parameter is not really valid.

The questions that arise are the following:

  1. Is it OK to throw an exception in the constructor? If not the solution would be easy: I could defer the search of valid properties to the first call to WriteLine(T record) or similar mehtod (lazy initialization).
  2. Is it OK to throw an exception caused by a generic type parameter? Or is it just better to leave the generated csv empty? There is no way I can constraint the generic parameter to valid types.
  3. And finally, if answer to question No. 2 is yes, what exception should I use? ArgumentException seems the better fit but its still not quite right.

Thank you.

Upvotes: 3

Views: 118

Answers (2)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

You can even throw an exception from the class constructor (aka static constructor). That way you can do your checks/initializations only once per T.

If the class constructor fails for CsvWriter<Foo>, you won't be able to even call the constructor of CsvWriter<Foo>.

If you're worried about proper argument typing, you could create a custom exception type. It's the cleanest solution. But I wouldn't worry about it that much since if you use the class constructor, your exception will be wrapped in a TypeInitializationException either way.

Upvotes: 2

David Crowell
David Crowell

Reputation: 3813

This is really something that should be a compile-time error, but the language doesn't support it.

1: Yes, go ahead and throw in the constructor. This fail-fast technique will make it less likely you ship bad code.

2: Throw as soon as possible. Don't create the file.

3: I'd create a subclass of InvalidOperationException. You may think of something better.

Also, I highly recommend writing a unit test not only for this class, but for any other code that ever instantiates it.

You may also want to re-think your design. Maybe an interface to give you the basics.

Upvotes: 1

Related Questions