Skip to content

Instantly share code, notes, and snippets.

@rudrathegreat
Forked from lambdamusic/Snipplr-25250.py
Last active December 28, 2018 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rudrathegreat/620f1c66514f3aca94679b8abd3ba484 to your computer and use it in GitHub Desktop.
Save rudrathegreat/620f1c66514f3aca94679b8abd3ba484 to your computer and use it in GitHub Desktop.
Error Handling in Python - Python 3
## Error handling in Python is done through the use of exceptions that are caught in try blocks and handled in except blocks. If an error is encountered, a TRy block code execution is stopped and transferred down to the except block, as shown in the following syntax:
data = 'Hello and welcome to Earth (if you are an alien)'
try:
f = open("test.txt")
except IOError:
print("Cannot open file.")
## In addition to using an except block after the try block, you can also use the finally block. The code in the finally block will be executed regardless of whether an exception occurs.
f = open("test.txt")
try:
f.write(data)
finally:
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment