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.py104 chars6 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.py256 chars13 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).
gistlibby LogSnag