Python Lesson 20: Error Handling

  1. Using try/except
  2. Using try/except/finally

Error handling is a good practice and it is a necessary skill when learning Python.

  • The try block lets you test a block of code for errors
  • The except block lets you handle the error in a more user friendly way
  • The finally block lets you execute code if an error occurs or not. Useful for closing files, connections, cleanup etc.…

Using Try/Except

#Will pass
name = "John"
try:
    print("Hello " + name)
except NameError:
    print("Missing a value for name")
#Will fail
try:
    print("Hello " + name)
except NameError:
    print("Missing a value for name")
Notebook Output

Using try/except/finally

name = "John"
try:
    print("Hello " + name)
except NameError:
    print("Missing a value for name")
finally:
    print("Have a nice day")
    del name
    
#Since name has been deleted it will fail
try:
    print("Hello " + name)
except NameError:
    print("Missing a value for name")
Notebook Output

Recommended Books