Errors

An exception is an event triggered when something goes wrong.

Error handling in Python is primarily done via exception handling, which is exceedingly easy to use and figure out. This is accomplished via 'try' and 'except', as follows.

try:
   open("nothing", 'r')
except:
   print("File not found.")

open() will throw an exception if the file 'nothing' is not found.

The problem with this is that there are many different kinds of exceptions which open() could throw, and some of them may not warrant the same response as others. This is solved by telling except which exception to handle case by case.

List of these built-in exceptions: https://docs.python.org/3/library/exceptions.html.

try:
   open("nothing", 'r')
except FileNotFoundError:
   print("Cannot open file: file not found")
except IsADirectoryError:
   print("Cannot open file: file is a directory")
except PermissionError:
   print("Cannot open file: permission denied")
except:
   print("Cannot open file: file cannot be accessed")

Usually instead of just leaving a catch-all except statement at the end, it is better to let the exception occur if the exception is hard to forsee and you can't be bothered to properly make a handler for it.

This same strategy can be applied across all situations in which errors may occur. It is, however, bad practice to obscure off-by-one errors with exceptions, or to obscure errors by handling exceptions that happen due to poor design. Readability must be kept in mind at all times.