Skip to content Skip to sidebar Skip to footer

Avoiding Multiple Try/except Blocks In Python

I have a working code but find that having numerous try/except blocks to handle exceptions very inefficient. Is there a better way to do this? The code that I am currently using i

Solution 1:

You have many sections of code that do basically the same thing, which violates the Don't Repeat Yourself (DRY) principle. The usual way to avoid that repetition is to write a function to hide the repetition.

defget_text_or_NA(container):
    try:
        result = container[0].getText()
    except:
        result = 'NA'return result

Then your basic code is

Age = get_text_or_NA(Age_find)
Tm = get_text_or_NA(Tm_find)
Lg = get_text_or_NA(Lg_find)

and so on.

You could similar means to remove other repetitions in your code--I'll leave those to you. And as the comment from @roganjosh states, you really should not use except: without giving an exception. Your way just hides all problem. Be more specific and hide only the exceptions you expect, so unexpected ones can be caught at a higher level.

Post a Comment for "Avoiding Multiple Try/except Blocks In Python"