Errors and exceptions
Python · 14 questions
Short notes
Key idea
An exception is Python's way of saying something went wrong. try/except lets you catch the ones you expect and decide what to do, instead of crashing.
Syntax
try:
qty = int(text)
except ValueError:
qty = 0
else:
print("parsed") # only if no error
finally:
print("always runs")
raise ValueError("amount must be positive")
Example
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_divide(10, 0)) # None
Common types: ValueError (bad value), KeyError (missing dict key), IndexError, TypeError (wrong type), FileNotFoundError.
Traps
- A bare
except:hides every bug, typos included. Name the exception you expect. - Don't wrap the whole program in one
try. Keep it around the line that can fail. - Read the last line of the traceback first: it names the error; the line above shows where.
- Raising early with a clear message beats a confusing error later.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
Which exception does
int("abc")raise? - Question 2medium
Why is
except:with no exception type usually a bad idea? - Question 3medium
What does this print?
steps = [] try: x = 10 / 2 except ZeroDivisionError: steps.append("except") else: steps.append("else") finally: steps.append("finally") print(len(steps)) - Question 4medium
What does this print?
raw = ["1999", "650", "abc", "", "499", "12.5"] bad = 0 for v in raw: try: float(v) except ValueError: bad += 1 print(bad) - Question 5hard
What does this print?
results = [] for a, b in [("10", "2"), ("10", "0"), ("ten", "2")]: try: results.append(int(a) // int(b)) except ZeroDivisionError: results.append("zero") except ValueError: results.append("bad") print(results)
Errors and exceptions
Errors and exceptions
Errors and exceptions
Errors and exceptions
Errors and exceptions
9 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.