Common Built-in Exceptions

45 min read Exception Handling

This is a free course. Log in to run the code exercises and track your progress.

Common Built-in Exceptions

ExceptionRaised whenExample
SyntaxErrorthe code breaks Python's grammar (before it runs)if x > 3 print(x)
ValueErrorthe type is right but the value is notint("abc")
TypeErroran operation gets the wrong type"5" + 2
ZeroDivisionErrordivision or modulo by zero7 % 0
NameErrora name is not definedprint(totl)
IndexErrora sequence index is out of range[1, 2][5]
KeyErrora dictionary key is missing{"a": 1}["b"]
FileNotFoundErroropening a file that does not exist for readingopen("none.txt")
EOFErrorinput() or pickle.load() reaches the end of the datapickle.load(f) after the last record
ImportErrora module or name cannot be importedfrom math import square

One except clause can catch several types written as a tuple, and as gives you the exception object with its message:

try:
    value = [10, 20, 30][int(input())]
except (ValueError, IndexError) as err:
    print("Bad position:", type(err).__name__)
Python exercise

Each input line is an expression a op b with integers and an operator +, -, *, / or %. Print the result of each, or the name of the exception it raises (ZeroDivisionError or ValueError). Stop at the line END.

ops = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b,
       "/": lambda a, b: a / b, "%": lambda a, b: a % b}
while True:
    line = input()
    if line == "END":
        break
    a, op, b = line.split()
    print(ops[op](int(a), int(b)))  # catch the errors and print their names

Log in to edit and run this code.