Common Built-in Exceptions
This is a free course. Log in to run the code exercises and track your progress.
Common Built-in Exceptions
| Exception | Raised when | Example |
|---|---|---|
SyntaxError | the code breaks Python's grammar (before it runs) | if x > 3 print(x) |
ValueError | the type is right but the value is not | int("abc") |
TypeError | an operation gets the wrong type | "5" + 2 |
ZeroDivisionError | division or modulo by zero | 7 % 0 |
NameError | a name is not defined | print(totl) |
IndexError | a sequence index is out of range | [1, 2][5] |
KeyError | a dictionary key is missing | {"a": 1}["b"] |
FileNotFoundError | opening a file that does not exist for reading | open("none.txt") |
EOFError | input() or pickle.load() reaches the end of the data | pickle.load(f) after the last record |
ImportError | a module or name cannot be imported | from 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__)
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 namesLog in to edit and run this code.