HowCanI: inlined exceptions

tgdeveloper at tgdeveloper at
Fri May 26 19:19:40 EDT 2000

In article <392EE821.714573DD at>,
  Pete Shinners <pete at> 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):
		return eval(exprString)
		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:

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
Before you buy.

More information about the Python-list mailing list