Errors and Exceptions

ITEC 4400/2160 Python Programming for Data Analysis,
Cengiz Günay

(License: CC BY-SA 4.0)

Prev - Python data structures, Next - Recursion

What are exceptions?

  • A way to break out of the linear execution of a program
  • Usually for an exceptional situation (e.g., an error)
  • Otherwise, it may cause your program to crash
  • Why not instead use if statements to catch errors?
  • Cleaner logic and execution, does not disrupt logic
  • Exception may arise from multiple places

Examples with if statements vs exceptions

If statement:

value = count_inputs(...)
if value < -1:
  print("Error in counting inputs!")
  exit -1
# now do stuff with value
...

Exception:

try:
  value = count_inputs(...)
  # now do stuff with value
  ...
except:
  print("Error in counting inputs!")
  raise

Exceptions in Python

  • All exceptions should be subclasses of BaseException
  • You can have multiple except clauses to catch specific exceptions:
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
Home