run multiple code blocks depending on "try" & "except" from previous block

Viewed 99

So, I am very unfamiliar with the "try" and :except" code lines and I am unsure if I am doing this correctly, but this is where I am.

try:
 code a
#
except Exception:
 code b
#
except:
 code c

So, what I am trying to do is for the browser to try "code a", and if "code a" is not found, then try "code b". If there is an easier way of doing this, please let me know. "code c" is the last line of code that I want to run after it has found either "code a" or "code b". Both "code a" and "code b" have browser.refresh() in it, of which I want it to keep refreshing the page until either "code a" or "code b" finds what it is looking for. But, when it does not find what it is looking for, it refreshes the page but says "Process finished with exit code 0" and not refreshing the page and restarting the script over again. It is supposed to search the page and if it does not find what it is looking for, refresh the page and try again until it finds it and then it continues to "code c". I have also tried "finally", but instead it continues to the "finally" before "code a" and "code b" actually find what it is looking for.

I have also tried this.

try:
  code a
except Exception:
  pass
#
try:
  code b
except Exception:
  pass
#
try:
  code c
except Exception:
  pass

Neither of these worked or me, they kept finishing the process without trying until it found either "code a" or "code b".

Any help would be great!

Thanks in advance!

3 Answers

This will keep trying to execute code_a and code_b until one of them runs without error, then will exit the main loop and run code_c.

found_code = False
while not found_code:
    try:
        code_a
        found_code=True
    except Exception:
        pass
    try:
        code_b
        found_code=True
    except Exception:
        pass
code_c

This question has already been answered but I believe break statements are easier than having a Boolean variable for the while loop. Also, the other answer will run both code a and code b each time the loop runs, while this code runs either a or b, which was requested in the question.

while True:
    try:
        code a
        break
    except:
        try:
            code b
            break
        except:
            pass
code c

Can use: suppress from: contexlib.

Try something like:

from contextlib import suppress


def do_dangerous(code_to_run):
    with suppress(Exception):
        code_to_run()
        return True
    return False


flag: bool = do_dangerous(code1) or do_dangerous(code2)
if flag:
    code3()

Or even shorter:

if do_dangerous(code1) or do_dangerous(code2):
   code3()
Related