Practice: Basic Error Understanding
Q1. Catch a zero division
Write code that divides 10 by 0 inside try and prints Cannot divide by zero when the error happens.
Goal: Catch an expected error.
Q2. Safe integer conversion
Convert the text "12a" with int(). If it fails, print Invalid number, otherwise print the number.
Goal: Handle ValueError.
Q3. Print the error name
Run 5 + "5" inside try and print only the name of the error class.
Goal: Read the error type.
Q4. Safe list access
Given items = [1, 2, 3], try to print items[10]. On IndexError print No such position.
Goal: Handle IndexError.
Q5. Dictionary default message
Given d = {"a": 1}, look up the key "b" inside try. On KeyError print Missing key b.
Goal: Handle KeyError.
Q6. Finally always runs
Write try with print(1), except for nothing, and a finally that prints done. Show that done is printed.
Goal: Use finally.
Q7. Raise your own error
Write a function check_age(age) that raises ValueError with the message Age cannot be negative when age is below 0. Call it with -1 inside try and print the message.
Goal: Raise exceptions.
Q8. Which line runs?
What is printed?
try:
print("A")
x = 1 / 0
print("B")
except ZeroDivisionError:
print("C")Goal: Trace try and except.
Q9. Else block
What is printed?
try:
n = int("7")
except ValueError:
print("bad")
else:
print(n + 1)Goal: Use else.
Q10. Error name output
What is printed?
try:
int("hello")
except Exception as e:
print(type(e).__name__)Goal: Recognise ValueError.
Q11. Order of messages
What is printed?
def f():
try:
return "try"
finally:
print("cleanup")
print(f())Goal: Understand finally.
Q12. Message text
What is printed?
try:
[1, 2][2]
except IndexError as e:
print(e)Goal: Read error messages.
Q13. Two except blocks
What is printed?
def run(v):
try:
return 10 / v
except ZeroDivisionError:
return "zero"
except TypeError:
return "type"
print(run(2))
print(run(0))
print(run("a"))Goal: Use several except blocks.
Q14. Fix the missing colon
This code has a SyntaxError. Fix it.
try
print(1)
except:
print(2)Goal: Fix syntax errors.
Q15. Fix the NameError
The program crashes with NameError. Fix it.
total = 5
print(totl)Goal: Fix NameError.
Q16. Fix the TypeError
The program crashes with TypeError. Fix it so it prints Age: 30.
age = 30
print("Age: " + age)Goal: Fix TypeError.
Q17. Fix the logic error
The code should print the average of 4 and 6 (5.0) but prints something else. Fix it.
a = 4
b = 6
print(a + b / 2)Goal: Find logic errors.
Q18. Traceback reading
In a traceback, which line tells you the kind of error?
Goal: Read a traceback.
Q19. Syntax versus runtime
Why does a SyntaxError stop the program before any line runs, while a ZeroDivisionError does not?
Goal: Separate syntax and runtime errors.
Q20. Why avoid bare except
Give one reason why except: with no error name is a bad habit.
Goal: Write safe error handling.