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?

  • 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. – Samwise Mar 27 '22 at 22:13

3 Answers3

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.

Lolrenz Omega
  • 163
  • 1
  • 7
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")
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
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")
S.B
  • 13,077
  • 10
  • 22
  • 49