473,386 Members | 1,835 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Throwing Exceptions from Property

Sek
Gurus,

I am wondering whether it is right to throw an exception from a
Property of an object.

To get into it further, is it okay to throw exception during 'get'
operation?

I was searching for MS articles on throwing exceptions. But, in vain.

I am curious to know more on this.

-Sek

Apr 11 '06 #1
15 3213
Not good. Because they wonder to get exception from the common
obj.Name = "name";

If u need to throw exception use method for this, it's more expected
Gurus,
I am wondering whether it is right to throw an exception from a
Property of an object.
To get into it further, is it okay to throw exception during 'get'
operation?

I was searching for MS articles on throwing exceptions. But, in vain.

I am curious to know more on this.


--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche

Apr 11 '06 #2
Sek
Thanks for the info.

But, how about throwing exception during a 'Set' operation. I don't see
any other way of converying the failure of 'Set' operation.

Apr 11 '06 #3
Why not? Properties are just syntactic candy for a method call. They are
actually method calls in the IL code. They are typically used to do pre
or post processing of the value to validate it. So it certainly could
throw an exception if the value is invalid.

Leon Lambert

Sek wrote:
Gurus,

I am wondering whether it is right to throw an exception from a
Property of an object.

To get into it further, is it okay to throw exception during 'get'
operation?

I was searching for MS articles on throwing exceptions. But, in vain.

I am curious to know more on this.

-Sek

Apr 11 '06 #4
Sek
Makes sense.

Thanks a lot for the explanation.

Apr 11 '06 #5
Michael Nemtsev wrote:
Not good. Because they wonder to get exception from the common
obj.Name = "name";

If u need to throw exception use method for this, it's more expected


On the contrary - one of the reasons for using a property rather than a
straight public field is to enable validation of the given value.

For instance, look at StringBuilder.Length, which is documented to
throw an exception if you give it an inappropriate value.

Jon

Apr 11 '06 #6
design issue, isn't it? We can call method from the set property
Not good. Because they wonder to get exception from the common
obj.Name = "name";

If u need to throw exception use method for this, it's more expected


On the contrary - one of the reasons for using a property rather than a
straight public field is to enable validation of the given value.

For instance, look at StringBuilder.Length, which is documented to
throw an exception if you give it an inappropriate value.


--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Apr 11 '06 #7
Michael Nemtsev wrote:
design issue, isn't it?
Absolutely - but I disagree with your design viewpoint that properties
shouldn't throw exceptions.
We can call method from the set property


But if that throws an exception, we're back to the point of contention
- whether it's okay for properties to throw exceptions or not.

Jon

Apr 11 '06 #8
HI,

"Michael Nemtsev" <Mi************@discussions.microsoft.com> wrote in
message news:DD**********************************@microsof t.com...
Not good. Because they wonder to get exception from the common
obj.Name = "name";
It's not only good but expected, how otherwise you will react to a wrong
value being assigned to a property?

If u need to throw exception use method for this, it's more expected


An exception is expected wherever an error occur. it does not matter where.

Apr 11 '06 #9
"Sek" <se****@gmail.com> wrote:
I am wondering whether it is right to throw an exception from a
Property of an object.


MyClass x = null;
string s = x.Name;

int[] x = new int[10];
int i = x[15];

If exceptions are reasonable even for value-getting, I think they're
fine also for property-getting.

--
Lucian
Apr 11 '06 #10
Sek,

The Framework Design Guidelines book recommends avoiding exceptions in
property getters. If a getter needs to throw an exception then it
should probably be refactored into a method. The rule does not apply
to setters or indexers though.

Brian

Sek wrote:
Gurus,

I am wondering whether it is right to throw an exception from a
Property of an object.

To get into it further, is it okay to throw exception during 'get'
operation?

I was searching for MS articles on throwing exceptions. But, in vain.

I am curious to know more on this.

-Sek


Apr 11 '06 #11

"Lucian Wischik" <lu***@wischik.com> wrote in message
news:jh********************************@4ax.com...
"Sek" <se****@gmail.com> wrote:
I am wondering whether it is right to throw an exception from a
Property of an object.


MyClass x = null;
string s = x.Name;

int[] x = new int[10];
int i = x[15];

If exceptions are reasonable even for value-getting, I think they're
fine also for property-getting.


As I explained elsewhere, there is a difference between exceptions caused by
the caller's carelessness (OK) and exception caused by the object failing to
fulfill its description as a possesor of a certain property (Not OK).

MyClass x says that it has a Name property. If the getter throws then it
lied and there is no way that the caller could avoid it.

int[] x never said it had 16 elements. If you treat it like its has then you
will get an exception. The caller can always check with if(x.Length >=16).
Apr 12 '06 #12
The general consensus here is that they're OK, and I agree with that.

Throw an exception whenever it makes sense to do so. That's a vague
definition, but generally I throw exceptions whenever I need to validate
anything.

If I need to validate input, I always thrown an exception. When I need
to validate output, I always throw an exception.

I might not be doing things correctly, but it seems to work okay for me.

jeremiah
Sek wrote:
Gurus,

I am wondering whether it is right to throw an exception from a
Property of an object.

To get into it further, is it okay to throw exception during 'get'
operation?

I was searching for MS articles on throwing exceptions. But, in vain.

I am curious to know more on this.

-Sek

Apr 13 '06 #13
"jeremiah johnson" <na*******@gmail.com> wrote in message
news:u2*************@TK2MSFTNGP05.phx.gbl...
The general consensus here is that they're OK, and I agree with that.

Throw an exception whenever it makes sense to do so. That's a vague definition, but generally I
throw exceptions whenever I need to validate anything.

If I need to validate input, I always thrown an exception. When I need to validate output, I
always throw an exception.

I might not be doing things correctly, but it seems to work okay for me.


While I do agree that you should throw an exception when it makes sense to do so, I also believe
that if you need to throw exceptions in your properties, you should at least consider refactoring
your design.

Let me Splain.

A classic case of needing validation is Dates and times.
Is the month between 1 and 12 (or is it 0 and 11)
Is the day between...
You get the idea.

Now look at the DateTime struct.
None of its properties throw an exception.
All of the validation (exception throwing) is in the constructor.

This goal is not always achievable, but in general, you should think about it.

my 2 cents
Bill
Apr 13 '06 #14
Bill Butler <qw****@asdf.com> wrote:
Let me Splain.

A classic case of needing validation is Dates and times.
Is the month between 1 and 12 (or is it 0 and 11)
Is the day between...
You get the idea.

Now look at the DateTime struct.
None of its properties throw an exception.
All of the validation (exception throwing) is in the constructor.

This goal is not always achievable, but in general, you should think about it.


That's just because none of its properties have setters - DateTime is
immutable. Immutability is great where appropriate, but it's far from
always appropriate.

There are plenty of other places in the framework which *do* validate
in properties and throw exceptions.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 14 '06 #15
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Bill Butler <qw****@asdf.com> wrote:
Let me Splain.

A classic case of needing validation is Dates and times.
Is the month between 1 and 12 (or is it 0 and 11)
Is the day between...
You get the idea.

Now look at the DateTime struct.
None of its properties throw an exception.
All of the validation (exception throwing) is in the constructor.

This goal is not always achievable, but in general, you should think about it.


That's just because none of its properties have setters - DateTime is
immutable. Immutability is great where appropriate, but it's far from
always appropriate.

There are plenty of other places in the framework which *do* validate
in properties and throw exceptions.


<grin>
Hi Jon,
I was well aware of the immutably factor when I posted. I went back and forth with myself about
using that particular example, but decided in favor of it due to all of the issues involved if you
allowed DateTime objects to have their properties set individually.
You are absolutely correct.I was just attempting to point out that sometimes it makes more sense to
Put your validation code in the constructor, or in a method.
If DateTime was an class and not a struct, you could still make a good argument for making it behave
in a similar fashion to the way it does now.
If you set the Day to 31....is that valid??? We don't know until we know what month.
What about 29 FEB ? IS it a leap year

Another thing you see frequently in the framework is properties that *Could* be integer values with
range validation. Instead they are refactored to take an object/struct that validated the range in
it's constructor.

I really don't disagree with you at all.
I am simply saying that you should at least *consider* refactoring if you run into a similar
situation.
I was just arguing in favor of exceptions in properties in another thread a couple of days ago ;^)

I guess I just like looking at both sides of the issue.

Bill

Apr 14 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Mark Oueis | last post by:
I've been struggling with this question for a while. What is better design? To design functions to return error codes when an error occures, or to have them throw exceptions. If you chose the...
21
by: mihai | last post by:
People say that is a bad technique to throw exception from constructors; and that the solution would be to create a function _create_ to initialize an object. What about copy constructors? How...
4
by: Sridhar | last post by:
Hi, I would like to know the general procedure to throw exceptions. Lets say I have a datagrid in my webpage and I am pulling the data for my webpage using a function. The function accepts...
5
by: GG | last post by:
Any thoughts on designing classes wheather to throw the exception and the consumer has to capture it on try catch or wrap all the methods in a main method This is the wrap logic MainMethod{ bool...
6
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows...
4
by: Jay Dee | last post by:
I have a query about throwing exceptions. To throw an exception I type something like: try { // do somthing } catch (ArgumentOutOfRangeException) {
3
balabaster
by: balabaster | last post by:
Hey all, this might seem somewhat remedial but I'm unable to find any documentation on it - it pertains to throwing exceptions within a DLL. I've written a DLL that contains a bunch of classes....
9
by: thagor2008 | last post by:
Is the behaviour of throwing exceptions in a unix signal handler defined? eg: void sighandler(int sig) { ... do something throw myobj; }
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.