I always hear people who say setters and getters should be fast and not throw exceptions.
Now, if it is true, how should I handle an invalid value passed to a setter, if not throwing an exception?
I always hear people who say setters and getters should be fast and not throw exceptions.
Now, if it is true, how should I handle an invalid value passed to a setter, if not throwing an exception?
As per MSDN
AVOID throwing exceptions from property getters.
Property getters should be simple operations and should not have any preconditions. If a getter can throw an exception, it should probably be redesigned to be a method. Notice that this rule does not apply to indexers, where we do expect exceptions as a result of validating the arguments.
Having said that, to me, it is absolutely fine to throw exception from setter
and normally getters
should never throw exception.
Consider a property as attribute or characteristic of the object. So when ever you are taking value of that attribute, you should get is without any exception. You would also want that, no one should be able to set invalid value to it, so it is fine to throw exception while setting the value.
Also as a good practice, do preserve the previous value if a property setter throws an exception. so that the integrity of the object is maintained. MSDN
You can find some good discussion here - https://softwareengineering.stackexchange.com/questions/16646/is-throwing-an-exception-from-a-property-bad-form
Actually, I think it is true mainly for constructors not to throw exceptions.
For getters/setters the problem is that bindings (like WPF) might cause some problems throwing exceptions in getters/setters.
But normally there is not that much that can cause an exception, except problems during development (pre-used objects being null?).
Validation problems should not be exceptions. Exceptions are cases that should be really unusual circumstances (like an expected file that is not existing, memory shortage). Input validation and checking if a user inputted file exist should not be exceptions for example.