Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception to throw when a property setter is not allowed?

Tags:

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):

  1. Is there a better pattern for me to use?
  2. If I should be using the above pattern, what exception to use?

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.

like image 399
Ray Avatar asked Sep 21 '11 11:09

Ray


People also ask

Should setters throw exceptions?

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.

Should properties throw exceptions?

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.

Which of the following properties of exception class is used to find the code that cause the exception?

The StackTrace property carries a stack trace that can be used to determine where the error occurs in the code.


1 Answers

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.

like image 180
Petar Minchev Avatar answered Oct 20 '22 23:10

Petar Minchev