To ensure some code runs no matter what errors occur, you can use a finally statement. The finally statement is placed at the bottom of a try/except statement. Code within a finally statement always runs after execution of the code in the try, and possibly in the except, blocks.
print(1 / 0)
print(“Divided by zero”)
print(“This code will run no matter what”)
Divided by zero
This code will run no matter what
Code in a finally statement even runs if an uncaught exception occurs in one of the preceding blocks.
print(10 / 0)
print(“This is executed last”)
This is executed last
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
NameError: name ‘unknown_var’ is not defined
CLICK ON THE BUTTON BELOW TO GO TO THE PYTHON MAIN COURSE PAGE.
©️ License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT