I would definitely argue that there is a flaw in the design if you feel the need to throw exceptions from a property setter or getter.
A property is an abstraction that represents something that is just a value. And you should be able to set a value without fearing that doing so could throw an exception.*
If setting the property results in a side effect, that that should really be implemented as a method instead. And if it doesn't produce any side effects, then no exception should be thrown.
One example already mentioned in a different answer is the Stream.Position
property. This does produce side effects, and may throw exceptions. But this property setter is basically just a wrapper around Stream.Seek
that you could call instead.
Personally, I believe that the position should not have been a writeable property.
Another example where you could be tempted to throw an exception from a property setter is in the validation of data:
public class User {
public string Email {
get { return _email; }
set {
if (!IsValidEmail(value)) throw InvalidEmailException(value);
_email = value;
}
}
But there is a better solution to this problem. Introduce a type representing a valid email address:
public class Email {
public Email(string value) {
if (!IsValidEmail(value)) throw new InvalidEmailException(value);
...
}
...
}
public class User {
public Email Email { get; set; }
}
The Email
class ensures that it cannot hold a value that is not a valid email address, and classes that need to store emails are relieved of the duty of validating them.
This also leads to higher cohesion (an indicator of good software design) - the knowledge about what an email address is, and how it is validated, exists only in the Email
class, which has only that concern.
* ObjectDisposedException is the only valid exception (no pun intended) I can think of at the moment.