Exception Handling

Catching problems that happen while a program is running, instead of letting them crash it.

Types of Errors

An exception is an error that occurs while a program is running, disrupting its normal flow. Python has many built-in exception types, each describing what specifically went wrong:

  • TypeError — an operation was used on the wrong type of value
  • ValueError — the right type was given, but with an invalid value
  • NameError — a variable doesn't exist in the current scope
  • IndexError — a sequence index is out of range
  • KeyError — a dictionary key doesn't exist
  • ZeroDivisionError — an attempt to divide by zero
  • FileNotFoundError — a file that was expected to exist doesn't
print(10 / 0)
ZeroDivisionError: division by zero
nums = [1, 2, 3]
print(nums[5])
IndexError: list index out of range

Try-Except & Finally

Code that might fail goes in a try block; code that handles the failure goes in an except block.

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except:
    print("Something went wrong.")
Enter a number: 0 Something went wrong.

Catching every error the same way hides what actually happened, though. It's better to catch specific exception types so each one gets a clear, useful response:

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ValueError:
    print("That wasn't a valid number.")
except ZeroDivisionError:
    print("Can't divide by zero.")
Enter a number: 0 Can't divide by zero.

An optional else block runs only if no exception was raised, and finally always runs no matter what — commonly used for cleanup, like closing a file whether or not something went wrong.

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ZeroDivisionError:
    print("Can't divide by zero.")
else:
    print("No errors occurred.")
finally:
    print("Done.")
Enter a number: 5 2.0 No errors occurred. Done.