Regular expression and exception

Arnaud Delobelle arnodel at googlemail.com
Sat Nov 15 09:31:39 EST 2008


Mr.SpOOn <mr.spoon21 at gmail.com> writes:

> Hi,
> I've never used exception before, but I think now it's time to start.
>
> I've seen that there is a list of  the built-in exceptions in the
> Python docs, but this explains the meaning of every exception. Does
> exist an inverted list? I mean, how may I know what kind of exception
> is going to raise my code? Shall I figure out by myself?

The interactive prompt will help you!

E.g. I want to know what exception arises when I try to add an int to a
string:

>>> 42 + 'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

Ah, it's a TypeError!

> Apart from this, in a method I check valid strings with a regular
> expression. I pass the string to the method and then Ii have something
> like:
>
> m = re.match('[1-9]$', my_string)
>
> I was thinking to put a try except here, so that:
>
> try:
>     m = re.match('[1-9]$', my_string)
> except:
>     print 'something...'
>
> But actually this doesn't work, because re.match just assign None to
> m, without raising anything.
>
> The only way seems to check with m.group(), so after I matched the
> string I should have:
>
> try:
>    m.group()
> except:
>    print 'error...'
>
> Or shall I put also the matching inside the try? Or am I completely wrong?

In this case re.match has been designed to return None if there are no
matches so there is no need to look for exceptions.  This is probably
because it is very common to use re.match(...) while expecting no match
so it is not really an 'exception'.  Just do

    m = re.match(...)
    if m is None:
        print 'error...'
    else:
        # Do something with m

HTH

-- 
Arnaud



More information about the Python-list mailing list