Groups | Blog | Home
all groups > c# > february 2006 >

c# : Exception handling in property.


archana
2/5/2006 11:09:54 PM
Hi all,

I am having c# application containing one property.

What i want is not to allow user to set null value to property.

So if in code user tries to set value as null i want to through
exception.

Can i do this, if yes then please tell me the way of throwing exception
in property and catching it in code where property is set.

Any help will be truely apprecaited.

Thanks in advnace.
Jon Skeet [C# MVP]
2/6/2006 12:00:00 AM
[quoted text, click to view]

You'd throw the exception in the same way you would from a method:

if (value==null)
{
throw new WhateverException();
}

Now, in terms of catching it - why would you catch it in the code where
the property is set? If you were going to catch it at that level, you'd
be far better off testing for nullity yourself first. You should almost
certainly be catching it much higher up the call stack - and you catch
an exception thrown by a property in the same way as you catch any
other exception. There's really no difference.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button