catching exceptions
Amit Khemka
khemkaamit at gmail.com
Sat Dec 16 07:06:00 EST 2006
On 16 Dec 2006 03:54:52 -0800, jm.suresh at no.spam.gmail.com
<jm.suresh at 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.
>
> 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.
More information about the Python-list
mailing list