When is it appropriate to throw an exception from within a property getter or setter? When is it not appropriate? Why? Links to external documents on the subject would be helpful… Google turned up surprisingly little.
C# – Best practices: throwing exceptions from properties
cexceptionnetproperties
Related Topic
- Java – What are the effects of exceptions on performance in Java
- Java – The case against checked exceptions
- C++ – Throwing exceptions from constructors
- Python – Proper way to declare custom exceptions in modern Python
- Python – Manually raising (throwing) an exception in Python
- Python – Catch multiple exceptions in one line (except block)
Best Answer
Microsoft has its recommendations on how to design properties at http://msdn.microsoft.com/en-us/library/ms229006.aspx
Essentially, they recommend that property getters be lightweight accessors that are always safe to call. They recommend redesigning getters to be methods if exceptions are something you need to throw. For setters they indicate that exceptions are an appropriate and acceptable error handling strategy.
For indexers, Microsoft indicates that it is acceptable for both getters and setters to throw exceptions. And in fact, many indexers in the .NET library do this. The most common exception being
ArgumentOutOfRangeException
.There are some pretty good reasons why you don't want to throw exceptions in property getters:
obj.PropA.AnotherProp.YetAnother
- with this kind of syntax it becomes problematic to decide where to inject exception catch statements.As a side note, one should be aware that just because a property is not designed to throw an exception, that doesn't mean it won't; it could easily be calling code that does. Even the simple act of allocating a new object (like a string) could result in exceptions. You should always write your code defensively and expect exceptions from anything you invoke.