Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
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.
raise StatementThe 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).
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:
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.
raise ... from NoneIf 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.
raise ValueError(). Prefer raise ValueError(f"Expected positive price, got {price}").TypeErrorValueErrorNotImplementedErrorRuntimeErrorraise "Error" is a fatal TypeError. You must raise an Exception instance or class.In modern Python, you must raise an instance or subclass of BaseException. Writing raise "Error" results in an immediate TypeError.
When re-raising or transforming an exception, use raise NewException(...) from err to preserve the causal chain for easier debugging.
Write a function dispense_item(inventory, item_name, count) that raises KeyError if the item is not in stock and ValueError if the requested count exceeds available stock.
raise is executed inside an except block?raise CustomError("Failed") from None?raise "Invalid Input"?In the next lesson, we will continue your intermediate Python journey with Creating Custom Exceptions (6: Exception Handling).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Try-Except-Else-Finally | Creating Custom Exceptions |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.