HowCanI: inlined exceptions

tgdeveloper at my-deja.com tgdeveloper at my-deja.com
Fri May 26 19:19:40 EDT 2000


In article <392EE821.714573DD at visionart.com>,
  Pete Shinners <pete at visionart.com> wrote:

> would use it extensively! i understand the problem
> here is that my "expression" is being evaluated
> before the function is getting called, so the
> exception is raised outside of my function.

Here's a fun way to do it:

==========

def catch(exprString, errcode = None):
	try:
		return eval(exprString)
	except:
		return errcode


if (__name__ == '__main__'):

	x = ['a', 'b', 'c']
	print catch("x[2]", "exceeded bounds")
	print catch("x[3]", "exceeded bounds")

==========

The output of this is:

c
exceeded bounds

==========

By passing the expression in as a string, it doesn't get evaluated
until inside the function, which evaluates it using eval().

If I were naming this, though, I wouldn't call it "catch" because then
I would tend to confuse it with C++ try/catch.





Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list