Exception handling in property.

A

archana

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.
 
J

Jon Skeet [C# MVP]

archana said:
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.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top