create try exept in python

To create a try except block in Python, you can use try keyword followed by a colon : and then a block of code to be attempted, followed by except keyword, the type of exception to be handled, another colon, and a block of code to be executed if the exception was raised.

Here is an example:

main.py
try:
    a = 10 / 0
    print(a)
except ZeroDivisionError:
    print("Division by zero is not allowed")
104 chars
6 lines

In the above example, we attempt to divide 10 by 0 which should throw a ZeroDivisionError. We handle it by printing a custom message to the console.

You can also have more than one except blocks to handle different exceptions. Additionally, you can add a final else block that will execute if no exceptions were raised. Finally, you can add a finally block that always executes regardless of whether any exceptions were raised or not.

main.py
try:
    f = open("file.txt", "r")
    a = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed")
except FileNotFoundError:
    print("File not found")
else:
    print(f.read())
    f.close()
finally:
    print("Execution complete")
256 chars
13 lines

In the above example, we try to open a file that doesn't exist (file.txt) and then divide 10 by 0. We raise two different exceptions. We handle these exceptions with two except blocks, and print an appropriate error message. At the end, we print the contents of the file (in the else block) and finally, we print a message saying that execution is complete (in the finally block).

related categories

gistlibby LogSnag