Exception confusion
Guido van Rossum
guido at python.org
Wed Aug 8 18:58:02 EDT 2001
Martin Sjögren <martin at strakt.com> writes:
> On Wed, Aug 08, 2001 at 01:41:10PM +0200, Martin von Loewis wrote:
> > Martin Sjögren <martin at strakt.com> writes:
>
> [snip]
>
> > III. Raising an exception in the form klass,value is the same
> > as raising it as klass(value)
>
> On the contrary, it isn't!
>
> You're saying that 'raise Exception, var' is the same as 'Exception(var)',
> but what about these two examples:
>
> raise Exception, 'foo'
>
> This is most certainly equivalent to "Exception('foo')" in that this
> holds:
> Exception('foo').args == ('foo',)
>
> No worries there!
>
> raise Exception, ('foo', 'bar')
>
> What happens now? This is NOT equivalent to "Exception(('foo', 'bar'))"
> since:
> Exception(('foo', 'bar')) == (('foo', 'bar'),)
> whereas "raise Exception, ('foo', 'bar') yields the tuple ('foo', 'bar')
> as exc.arg!
>
> [snip more]
>
> All I'm asking is WHY tuples are handled differently? In my case I have
> an exception that may be raised either with a tuple or a string. Right now
> I have to do this:
>
> except MyException, exc:
> if len(exc.args) == 0:
> arg = None
> elif len(exc.args) == 1:
> arg = exc.args[0]
> else:
> arg = exc.args
>
> Why-oh-why do exceptions work like this? :(
(1) Why? To make it easy to raise an exception with multiple
arguments without using the E(a, b, c) notation, and also easy
to raise an exception with a single argument. This was important
way back when we were encouraging folks to convert their
string-based exceptions to class-based exceptions.
(2) Workaround? When you want to raise an exception with a single
argument that's a tuple, add a singleton tuple around it:
raise E, (a,)
Or, of course, you can write
raise E(a)
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list