473,386 Members | 1,694 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.

catching exceptions

Hi, In the following program, I have a class Test which has a property
x. Its setx function gets a string value and converts it into a float
and stores into it.

class Test(object):
def _getx(self):
return self._x
def _setx(self,strvalue):
try:
self._x = float(strvalue)
except ValueError:
print 'Warning : could not set x attribute to %s' %
strvalue
x = property(_getx,_setx)
def func1(value):
a = Test()
try:
a.x = value
except ValueError:
#Pop up a error window.
print 'This is second catch'
func1('12')
func1('12e1')
func1('a')

func1('12')
func1('12e1')
func1('a')
>>func1('a')
Warning : could not set x attribute to a

I am looking for a way to call func1's exception handler also.
Basically I want to have the class's error handler as the basic text
based one, and in the calling side, If I have gui, I will pop-up a
window and say the error message.
One solution is to remove the exception handling inside the class and
leave the entire thing to the caller (software people call this
client?) side -- if the caller has access to gui it will use gui or
else will print the message. Any other way?

--
Suresh

Dec 16 '06 #1
7 1527
On 16 Dec 2006 03:54:52 -0800, jm*******@no.spam.gmail.com
<jm*******@gmail.comwrote:
Hi, In the following program, I have a class Test which has a property
x. Its setx function gets a string value and converts it into a float
and stores into it.

class Test(object):
def _getx(self):
return self._x
def _setx(self,strvalue):
try:
self._x = float(strvalue)
except ValueError:
print 'Warning : could not set x attribute to %s' %
strvalue
x = property(_getx,_setx)
def func1(value):
a = Test()
try:
a.x = value
except ValueError:
#Pop up a error window.
print 'This is second catch'
func1('12')
func1('12e1')
func1('a')

func1('12')
func1('12e1')
func1('a')
>func1('a')
Warning : could not set x attribute to a

I am looking for a way to call func1's exception handler also.
Basically I want to have the class's error handler as the basic text
based one, and in the calling side, If I have gui, I will pop-up a
window and say the error message.
One solution is to remove the exception handling inside the class and
leave the entire thing to the caller (software people call this
client?) side -- if the caller has access to gui it will use gui or
else will print the message. Any other way?
If I gather correctly, i guess in case of errors/exceptions in a class
function, you want to get the error string. One thing that comes
straight to my mind is, in such a case use a return statement in
functions with two arguments.

for example:
def foo(self, value):
try:
a.x = value
return True, ''
except ValueError: return False, 'Float conversion error: %s' %(value)

and when ever u call the function, check the first return value, It is
false then alert/print the error message.

HTH,
amit.
--
----
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
Dec 16 '06 #2
On Sat, 16 Dec 2006 03:54:52 -0800, jm*******@no.spam.gmail.com wrote:
Hi, In the following program, I have a class Test which has a property
x. Its setx function gets a string value and converts it into a float
and stores into it.
[snip code]

Python isn't Java. Are you sure you need properties?

I am looking for a way to call func1's exception handler also.
Basically I want to have the class's error handler as the basic text
based one, and in the calling side, If I have gui, I will pop-up a
window and say the error message.
One solution is to remove the exception handling inside the class and
leave the entire thing to the caller (software people call this
client?) side -- if the caller has access to gui it will use gui or
else will print the message. Any other way?
The exception is consumed by the try...except block inside the class,
so func1 never sees the exception. It might as well not exist.

Generally, you should keep your class as simple as possible. It shouldn't
try to manage any exception it can't recover from. In your case, the class
can't recover from a failure of float(strvalue), so it shouldn't consume
the exception. Two ways of doing that:

def _setx(self, strvalue):
self._x = float(strvalue) # just let the exception propagate

or

def _setx(self, strvalue):
try:
self._x = float(strvalue)
except ValueError:
raise SomeError('could not set x attribute to %s' % strvalue)

where SomeError should be either ValueError or possibly some custom
exception (say, MyClassException).

In either case, the error handling is separate from the object that
generates the error. And that is as it should be. Now your class can
remain the same, no matter how the rest of your program handles the
exception.

By the way, if you want your class to generate warnings, perhaps you
should investigate the Warnings module:

import warnings
help(warnings)

--
Steven.

Dec 16 '06 #3
On Sat, 16 Dec 2006 17:36:00 +0530, Amit Khemka wrote:
If I gather correctly, i guess in case of errors/exceptions in a class
function, you want to get the error string. One thing that comes
straight to my mind is, in such a case use a return statement in
functions with two arguments.

for example:
def foo(self, value):
try:
a.x = value
return True, ''
except ValueError: return False, 'Float conversion error: %s' %(value)

and when ever u call the function, check the first return value, It is
false then alert/print the error message.
Oh lordy, that is _so_ 1980s programming practice!!!

I'm not saying that it is never a good idea, but avoiding that sort of
thing is one of the reasons exceptions were created!
--
Steven.

Dec 16 '06 #4

Steven D'Aprano wrote:
On Sat, 16 Dec 2006 03:54:52 -0800, jm*******@no.spam.gmail.com wrote:
Hi, In the following program, I have a class Test which has a property
x. Its setx function gets a string value and converts it into a float
and stores into it.

[snip code]

Python isn't Java. Are you sure you need properties?
I do not know Java. But, object.x = value looks much better than
object.set_x(value) . Is there any harm in doing it, provided I have to
do more than just storing the value.
>
I am looking for a way to call func1's exception handler also.
Basically I want to have the class's error handler as the basic text
based one, and in the calling side, If I have gui, I will pop-up a
window and say the error message.
One solution is to remove the exception handling inside the class and
leave the entire thing to the caller (software people call this
client?) side -- if the caller has access to gui it will use gui or
else will print the message. Any other way?

The exception is consumed by the try...except block inside the class,
so func1 never sees the exception. It might as well not exist.

Generally, you should keep your class as simple as possible. It shouldn't
try to manage any exception it can't recover from. In your case, the class
can't recover from a failure of float(strvalue), so it shouldn't consume
the exception. Two ways of doing that:

def _setx(self, strvalue):
self._x = float(strvalue) # just let the exception propagate

or

def _setx(self, strvalue):
try:
self._x = float(strvalue)
except ValueError:
raise SomeError('could not set x attribute to %s' % strvalue)

where SomeError should be either ValueError or possibly some custom
exception (say, MyClassException).

In either case, the error handling is separate from the object that
generates the error. And that is as it should be. Now your class can
remain the same, no matter how the rest of your program handles the
exception.

By the way, if you want your class to generate warnings, perhaps you
should investigate the Warnings module:

import warnings
help(warnings)
I will go through it. Thanks a lot.
>
--
Steven.
Dec 16 '06 #5
On Sat, 16 Dec 2006 05:24:28 -0800, jm*******@no.spam.gmail.com wrote:
Hi, In the following program, I have a class Test which has a property
x. Its setx function gets a string value and converts it into a float
and stores into it.

[snip code]

Python isn't Java. Are you sure you need properties?

I do not know Java. But, object.x = value looks much better than
object.set_x(value) . Is there any harm in doing it, provided I have to
do more than just storing the value.
Why write set_x in the first place if all it does is set x? Why not just
have an attribute x and just write obj.x = value? What advantage are you
gaining?

One good use of properties is when you need attribute x to be calculated
on the fly. But there are costs as well: accessing a property is more
expensive than just accessing an attribute (accessing a property means
that not only do you access an attribute, but you also run a method). That
might not matter if your getter and setter are simple enough. Another cost
is that you have to write the code in the first place, and then you
have to test it: your class becomes bigger and more complicated. One
reason why getters and setters are looked at suspiciously is that in the
Java world, they frequently lead to bloated code. If you gain no benefit
from that complexity, why pay for it?

I'm not telling you "don't use properties" -- I'm merely telling you to
think about why you are using getters and setters in the first place, and
be sure that you are gaining benefit from them.

I'm suspicious about your example, because your getter simply looks up a
private attribute and returns it. Your setter does barely more work: it
calls float. I'm guessing that your intention is to try to ensure that
obj.x is only ever a float. But Python isn't designed for that sort of
strong type checking. It is very, very hard (possibly impossible) to
ensure calling code can't abuse your classes, and type-checking languages
only protect against one small set of potential abuse anyway. The usual
Python philosophy is not to bother, and instead rely on good unit testing
to test for all bugs, not just type bugs.

Your class as a tool. All tools can be used or misused. It isn't the
responsibility of the tool to protect you from misusing the tool (because
it can't, even if you wanted it to -- the best it can do is protect you
from some misuses). It is the responsibility of whoever uses the tool to
not misuse it.

In practice, what that often (but not always) means is that if you have an
attribute x that needs to be a float, your class is entitled to assume it
will always be a float, and the code that uses your class is responsible
for making sure that it never stuffs a non-float into x. If it does,
that's a bug in the caller, not in your class, and is best caught by unit
testing.

(But does x really need to be a float? Maybe it only needs to be an object
that acts like a float.)

That's just something for you to think about.

--
Steven.

Dec 17 '06 #6
On 16 dic, 10:24, "jm.sur...@no.spam.gmail.com" <jm.sur...@gmail.com>
wrote:
Python isn't Java. Are you sure you need properties?
I do not know Java. But, object.x = value looks much better than
object.set_x(value) . Is there any harm in doing it, provided I have to
do more than just storing the value.
You've provided the answer: properties are OK if you need to do "more"
that just store the value. Else, they're a waste of programmer and
processor time.
That was not clear on your original post.

--
Gabriel Genellina

Dec 17 '06 #7
jm*******@no.spam.gmail.com wrote:
>
class Test(object):
...
def _setx(self,strvalue):
try:
self._x = float(strvalue)
except ValueError:
print 'Warning : could not set x attribute to %s' % strvalue
...
I think what you are looking for is:
class Test(object):
...
def _setx(self, strvalue):
try:
self._x = float(strvalue)
except ValueError:
print 'Warning : could not set x attribute to %s' % (
strvalue)
raise # re-raise the exception that got us here.
...

--Scott David Daniels
sc***********@acm.org
Dec 19 '06 #8

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

Similar topics

1
by: Rolf | last post by:
I understand a compilation error occurs when a method that throws no exceptions is the only code in a try block. What I don't understnad is why I can specify the catching of an Exception for a...
2
by: Keith Bolton | last post by:
I am handling exceptions currently using try, except. Generally I don't handle specific exceptions and am catching all. Then if an exception occurs, I would like to capture that error string....
15
by: Steven Reddie | last post by:
I understand that access violations aren't part of the standard C++ exception handling support. On Windows, a particular MSVC compiler option enables Microsoft's Structured Exception Handling...
8
by: Adam H. Peterson | last post by:
Hello, I sometimes find myself writing code something like this: try { Derived &d=dynamic_cast<Derived&>(b); d.do_something_complicated(); // etc.... } catch (std::bad_cast) { throw...
7
by: cmay | last post by:
FxCop complains every time I catch System.Exception. I don't see the value in trying to catch every possible exception type (or even figuring out what exceptions can be caught) by a given block...
12
by: Vasco Lohrenscheit | last post by:
Hi, I have a Problem with unmanaged exception. In the debug build it works fine to catch unmanaged c++ exceptions from other dlls with //managed code: try { //the form loads unmanaged dlls...
7
by: Derek Schuff | last post by:
I'm sorry if this is a FAQ or on an easily-accesible "RTFM" style page, but i couldnt find it. I have some code like this: for line in f: toks = line.split() try: if int(toks,16) ==...
5
by: Simon Tamman | last post by:
I have an object named DisasterRecovery. The Ctor of this object is this: private DisasterRecovery() { Application.ThreadException+= new...
12
by: Karlo Lozovina | last post by:
I'm not sure if Python can do this, and I can't find it on the web. So, here it goes: try: some_function() except SomeException: some_function2() some_function3() ...
3
by: john | last post by:
I wrapped some fortran code using F2PY and need to be able to catch fortran runtime errors to run the following: # "grid" is a wrapped fortran module # no runtime errors incurred when run with...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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.