0

I want to control the error just printing it but continuing with the rest, por example:

try:
 list =('a',2,3,5,6,'b',8)

 print(list[8])
 print("continue execution")
except:
  print("An exception occurred")

It just will print the error but not the continue execution, is possible to continue even after exception?

1
  • Unrelated to your question, but it's a bad idea to reassign builtin names like list. It's doubly bad here because you're not even assigning it to a list, you're assigning it to a tuple. Commented Mar 27, 2022 at 22:13

3 Answers 3

4

What is missing and you're looking for is the finally instruction. Syntax:

try:
    #search for errors
except:
    #if errors found, run this code
finally:
    #run this code no matter if errors found or not, after the except block

The finally block contains the code that will be run after the except block, no matter if errors were raised or not.

Sign up to request clarification or add additional context in comments.

Comments

2

See if this rearrangement of your own code helps:

list =('a',2,3,5,6,'b',8)

try:
 print(list[8])
except:
  print("An exception occurred")

print("continue execution")

Comments

0

If it matters for you to "print continue" right after exception occurrence , then you can put whatever you want to do before exception in a "bool function" and then inside the "try" check if function succeed or not.it means "if error occurred continue ,else show "An exception occurred".

try:
    assert doStuff() == False
    print("continue execution")
except:
    print("An exception occurred")

1 Comment

Better to use is instead of == with True and False.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.