.NET Exceptions – Is Throwing an Exception from a Property Bad Form?

exceptionsnet

I've always been of the mindset that properties (ie, their set/get operations) should be fast/immediate and failure-free. You should never have to try/catch around getting or setting a property.

But I'm looking at some ways to apply role-based security on the properties of some objects. For instance an Employee.Salary property. Some of the solutions I've run across that others have tried (one in particular is the AOP example here) involve throwing an exception if the accessor doesn't have the right permissions – but this goes against a personal rule that I've had for a long time now.

So I ask: am I wrong? Have things changed? Has it been accepted that properties should be able to throw exceptions?

Best Answer

when you set the value of a property, throwing an exception on an invalid value is fine

getting the value of a property should (almost) never throw an exception

for role-based access, use different/dumber interfaces or facades; don't let people see things they can't have!