Jasi
Jasi

Reputation: 463

Python - AttributeError - How to properly force use of existing exception

I get the Error (obfuscated the path a little bit):

ERROR: (AttributeError) 'NoneType' object has no attribute 'group'
Traceback (most recent call last):
  File "/home/user/nananana/nananana/batman.py", line 168, in main
    url = result.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

The code part is as follows:

result = re.search('(http.*?.+txt)',url)
url = result.group(1)

So, I get a line that contains an url. I try to extract the URL that starts with http ort https and ends on .txt with at least one character or - or _ or . in between.

The problem is that sometimes I get the above error. I assume it means that the re.search was unsuccessful. Can I somehow ask if the result.group() is possible and if not let it run into one of my standard exception? The last part here being the key question.

except: 
  status = 'error'
  submitError2DB(db, fullurl, status, host, ip, txtname)
  print "\tAn unknown error occured. Fix needed.\nFailed.\n"

I only found the brilliant example to just do an:

raise Exception("I know python!")

but that's just not what I need.

Upvotes: 1

Views: 296

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

You can check if the result is not None like this

if result is not None:
    url = result.group(1)
else:
    raise Exception("No match")

In your words, if the result is not None, result.group is possible, otherwise an exception with text No match will be raised.

Upvotes: 2

Related Questions