I have a base class that has a virtual property:
public virtual string Name { get; set; }
then I have a derived class that overrides only the getter of the property
public override string Name { get { return "Fixed Name"; } }
The problem is this only overrides the getter. If someone calls the setter the base class setter will get called, and the caller won't know that it's ineffective.
So I thought I'd do something like:
public override string Name { get { return "Fixed Name"; } set { throw new Exception(); } //which exception type? }
So two (related questions):
Edit: Some reasons why one exception would be preferred over another would be good. My co-worker and I have had the same argument between NotSupported
and InvalidOperation
.
Yes, throw the exception in the setter. If your code throws IllegalArgumentException at some later point in time, it would be confusing to the caller. From the docs: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
As a rule of thumb, property getters and setters that are "late binding" should not throw exceptions, while properties with exclusively "early binding" should throw exceptions when the need arises.
The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code.
Throw NotSupportedException exception. Quote from the link:
There are methods that are not supported in the base class, with the expectation that these methods will be implemented in the derived classes instead. The derived class might implement only a subset of the methods from the base class, and throw NotSupportedException for the unsupported methods.
My opinion is that InvalidOperationException is not a correct option. Quote from MSDN:
The exception that is thrown when a method call is invalid for the object's current state.
There is nothing about current state in your situation. It is that the class contract does not support the operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With