Leo505
Leo505

Reputation: 107

Overuse of try and except in python code when using regex

I think i am over using try and except in my code. It's pretty much everywhere, where i have regexp matching. If it does not find the regex, it throws an exception, so i use the try and except to capture this to prevent my code from crashing. Example of what i'm talking about.

try:
    Output = "John Bob Charlie"
    match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash
except:
    print("Darn, no John")

Is there a better way of doing this or is this normal?? I'm new to Python and coming from Perl, a simple

if match{
print('we have found John')
}

Was all i needed.

Thanks in advance

Upvotes: 0

Views: 1511

Answers (3)

You could simply use an if statement to check whether there is any match

Output = "John Bob Charlie"
match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash

if match:
    # Do Something here 
else:
    print("Darn, no John")

You could refer the regex documentation here where a simple if statement is used

Upvotes: 2

Daniel
Daniel

Reputation: 42758

This does not work, because re.search returns None if the expression is not found.

Instead of try-except use if:

Output = "John Bob Charlie"
match = re.search(r'John', Output, re.M|re.I)
if not match:
    print("Darn, no John")

Upvotes: 1

thisshri
thisshri

Reputation: 642

I would say use exception for the cases where there is an exception (something unknown or unexpected). For example, you are calling an external API to fetch some data and the API throws an exception.

In your case, you should just go with:

if not match:
    return ('Darn, no John')
# here you can do whatever you want to do with Output variable.

Upvotes: 1

Related Questions