
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Python's try, except, else, and finally blocks enable developers to test code for errors, handle exceptions, execute code when no error occurs, and release external resources, respectively. Examples of using these blocks to handle nameerrors and other exceptions.
Typology: Cheat Sheet
1 / 1
This page cannot be seen from the preview
Don't miss anything!
try: print(x) except: print("An exception occurred") Since the try block raises an error, the except block will be executed. Without the try block, the program will crash and raise an error:
print(x)
You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources. try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") finally: print("Program did not run")