Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing multiple try and except in python

I want to know what is the most elegant way of writing try..except statements in python. Assume I have this code:

with open(sys.argv[1]) as f:
    for line in f:
        try:
            do_1(line)
        except:
            pass
        try:
            do_2(line)
        except:
            pass
        try:
            do_3(line)
        except:
            pass
        ...
        ...

What is the best way of writing this? My actions are sequential. However, if do_1 fails I still want to perform do_2. If all of them are in one try..except block, then if do_1 fails, I will never reach do_2. Is this the right way, or can I have one except for all of d0_i actions?

like image 924
Nick Avatar asked Apr 30 '26 12:04

Nick


1 Answers

It's simple enough to write this as a loop:

for action in [do_1, do_2, do_3, ...]:
    try:
        action(line)
    except AppropriateExceptionType:
        pass
like image 134
user2357112 supports Monica Avatar answered May 02 '26 02:05

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!