Practice: Raising Exceptions
Q1. Raise on negative
Write a function check(n) that raises ValueError('negative') if n < 0, else returns n. Call it with -1 inside try and print the message.
Goal: Raise stops the function and the handler prints the message.
Q2. Type check
Write a function double(x) that raises TypeError('need int') when x is not an int. Show the message for double('a').
Goal: isinstance checks the type before use.
Q3. Re-raise
Write code where int('z') fails, the except prints 'seen' and then re-raises; an outer try prints 'outer'.
Goal: A bare raise passes the same error upward.
Q4. Chain the cause
Write code that catches ZeroDivisionError from 1/0 and raises RuntimeError('math failed') from it. Catch the RuntimeError and print the type name of its __cause__.
Goal: __cause__ holds the original exception.
Q5. Assert message
Write code that runs assert 1 > 2, 'math is broken' inside try and prints the AssertionError text.
Goal: A false assert raises AssertionError with the message.
Q6. Validate a list
Write first(items) that raises IndexError('empty list') if items is empty, otherwise returns items[0]. Print first([9,8]) and the error for first([]).
Goal: Raise IndexError with a message for the empty case.
Q7. Which prints
What does this print?
try:
raise ValueError('bad')
except ValueError as e:
print('got', e)Goal: Read raise output.
Q8. Flow stops
What does this print?
def f():
print('a')
raise KeyError('k')
print('b')
try:
f()
except KeyError:
print('c')Goal: Understand flow after raise.
Q9. Bare raise order
What does this print?
def g():
try:
raise ValueError('x')
except ValueError:
print('1')
raise
try:
g()
except Exception:
print('2')Goal: Trace re-raise.
Q10. Cause name
What does this print?
try:
try:
int('q')
except ValueError as a:
raise TypeError('wrapped') from a
except TypeError as b:
print(b, type(b.__cause__).__name__)Goal: Read __cause__.
Q11. Assert passes
What does this print?
x = 5
assert x > 0, 'positive needed'
print('ok')Goal: Know assert when true.
Q12. Class vs instance
What does this print?
try:
raise KeyError
except KeyError as e:
print(repr(str(e)), e.args)Goal: Raise a class.
Q13. Fix the string raise
This code is broken. Fix it so it prints the message. try: raise 'bad value' except ValueError as e: print(e)
try:
raise 'bad value'
except ValueError as e:
print(e)Goal: Raise real exceptions.
Q14. Fix the bare raise
This code fails with a RuntimeError about no active exception. Make it print 'handled'.
def stop():
raise
try:
stop()
except ValueError:
print('handled')Goal: Know when bare raise works.
Q15. Fix the assert input check
This program should reject a negative age even when run with python -O. Fix it so it prints 'rejected'.
age = -3
try:
assert age >= 0
except AssertionError:
print('rejected')Goal: Avoid assert for validation.
Q16. Why from?
Explain in one or two sentences why you would write raise AppError('x') from err instead of just raise AppError('x') inside an except block.
Goal: Explain chaining.
Q17. Exception or return code
Give one reason raising an exception is better than returning -1 for invalid input.
Goal: Compare error styles.
Q18. Safe division wrapper
Write divide(a, b) that raises ValueError('b must not be zero') when b == 0 else returns a / b. Print divide(9, 3) and then the error message for divide(1, 0).
Goal: The function guards its own contract.
Q19. Withdraw money
Write withdraw(balance, amount) that raises ValueError('insufficient funds') if amount > balance, else returns balance - amount. Print withdraw(100, 30) and the error for withdraw(10, 50).
Goal: The error message explains the problem.