Raising Exceptions
Raising Exceptions in Python
While Python automatically raises exceptions when illegal runtime operations occur (like dividing by zero or indexing out of bounds), professional Python developers also intentionally trigger exceptions using the raise statement. Raising exceptions allows functions to reject invalid parameters, signal invariant violations, and propagate contextual error messages up the execution call stack.
1. The raise Statement
The raise keyword stops normal sequential execution and signals an exception. You can raise any instance or subclass of BaseException (almost always a subclass of Exception).
2. Re-raising Exceptions (Propagating After Logging)
Sometimes an except block needs to log diagnostic information, clean up temporary data, or execute metrics tracking, but still allow the exception to propagate to caller functions.
A bare raise statement inside an except clause re-raises the active exception currently being handled:
3. Exception Chaining: raise ... from ...
When building modular software or library wrappers, you often want to transform a low-level implementation error into a meaningful domain-level exception while preserving the original diagnostic cause.
Python supports Exception Chaining using the from clause:
When Python prints the traceback for this, it explicitly shows:
The original error is preserved in the __cause__ attribute of the new exception.
4. Suppressing Context with raise ... from None
If the low-level exception exposes sensitive internal details (like database credentials, internal server IPs, or confusing library internals) that would confuse API consumers, suppress the chain using from None:
Now, the traceback will only show ValueError: PIN must consist of 4 to 6 numeric digits. without the secondary "During handling of the above exception..." message.
5. Defensive Programming Best Practices
- 1Always include informative error messages: Avoid
raise ValueError(). Preferraise ValueError(f"Expected positive price, got {price}"). - 2Choose the most appropriate built-in exception:
- Bad argument type:
TypeError - Bad argument value/range:
ValueError - Feature not ready:
NotImplementedError - State violation:
RuntimeError
- 1Never raise strings: In modern Python,
raise "Error"is a fatalTypeError. You must raise anExceptioninstance or class.
Multiple Choice Questions
1. Which keyword is used in Python to intentionally trigger an exception?
A. throw B. fire C. raise D. emit Answer: C Explanation: In Python, the raise keyword is used to trigger exceptions (unlike Java/JavaScript which use throw).
2. What happens when a bare raise is executed inside an except block?
A. It resets all global variables B. It re-raises the active exception being handled, preserving the traceback C. It raises a RuntimeError D. It silently suppresses the error Answer: B Explanation: A bare raise re-propagates the active exception that was caught by the current except block.
3. How do you explicitly chain a new exception to an underlying causal exception?
A. raise NewError(msg).with_cause(old_err) B. raise NewError(msg) from old_err C. raise NewError(msg) -> old_err D. raise NewError(msg) under old_err Answer: B Explanation: Python's raise NewException from original_exception syntax chains the two exceptions, setting the __cause__ attribute.
4. What is the effect of writing raise CustomError("Failed") from None?
A. It causes Python to enter an infinite loop B. It suppresses the original exception's traceback context from being displayed C. It deletes the error log D. It returns None instead of raising an error Answer: B Explanation: from None explicitly suppresses the previous exception context (__context__), showing only the newly raised exception in tracebacks.
5. What error is raised if a programmer attempts to execute raise "Invalid Input"?
A. ValueError B. TypeError C. SyntaxError D. StringException Answer: B Explanation: In Python 3, exceptions must inherit from BaseException. Raising a string or any non-exception object raises a TypeError: exceptions must derive from BaseException.
Creating Custom Exceptions
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Try-Except-Else-Finally | Creating Custom Exceptions |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.