14.4Raising Exceptions
Covers IGNOU MCS-201 §14.4
Exceptions are not only raised by Python; your own code can raise them when it detects a situation it cannot accept, such as a negative age or an empty order. This turns silent bad data into a clear, catchable error.
The raise statement
raise ExceptionClass("message describing the problem")raisecreates the exception and starts the same process as a built-in error: the rest of the block is skipped and Python looks for a handler.- Choose the built-in class that fits:
ValueErrorfor an unacceptable value,TypeErrorfor a wrong type,KeyErrororLookupErrorfor something not found. - A bare
raiseinside anexceptblock re-raises the exception being handled, after, for example, logging it.
Key takeaways
raisesignals an error from your code.- Choose a fitting built-in exception and include a helpful message.
- A raised exception is handled exactly like a built-in one.
- A bare
raiseinexceptre-raises the current exception.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function set_age(age) that raises TypeError if age is not an integer and ValueError if it is outside 0 to 120, and show a call that handles both.
Show worked answer
def set_age(age): with if not isinstance(age, int): raise TypeError("age must be an integer"), if not 0 <= age <= 120: raise ValueError("age must be between 0 and 120"), and return age. Call: try: set_age(150) with except (TypeError, ValueError) as e: print("Invalid age:", e), which prints Invalid age: age must be between 0 and 120.