Use `raise ExceptionType('message')` to explicitly trigger built-in errors like `ZeroDivisionError` or `ValueError` when business or input rules fail, and bare `raise` inside an `except` block to re-throw the active exception. The `assert condition, 'message'` statement tests internal invariants and raises `AssertionError` if false, though running Python with `-O` strips assertions. For domain-specific validation, subclass `Exception` with `class MyError(Exception): pass` and raise it directly.
- 1. Triggering Built-In Exceptions and Re-Raising with raise
- 2. Using assert for Developer Sanity Checks vs. Input Validation
- 3. Designing Custom Exception Subclasses for Clean Error Handling
- 4. Validating Inputs with raise, assert, and Custom Exceptions
- 5. Comparison of Exception Raising Mechanisms in Python
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. Triggering Built-In Exceptions and Re-Raising with raise
Python automatically raises `ZeroDivisionError` when dividing by zero, `IndexError` on out-of-bounds sequence access, and `TypeError` on incompatible operands. However, defensive functions often validate arguments early and call `raise` manually so callers receive a clear diagnostic before corrupt state propagates. Passing a class or instance such as `raise ZeroDivisionError('Denominator cannot be 0')` immediately halts the current block and searches upward for a matching `except` handler. Inside an `except` block, writing a bare `raise` without arguments re-throws the exact active exception object while preserving its original stack trace—useful when a function logs an error locally and still needs the caller to handle the failure. Avoid writing `raise 'error text'`, which fails in Python 3 with a `TypeError` because every raised object must inherit from `BaseException`.
- Use `raise ValueError(...)` for invalid argument values and `raise ZeroDivisionError(...)` for zero divisors.
- Bare `raise` works only while an exception is active inside an `except` clause.
- Raising a plain string is illegal in Python 3; always raise an exception class or instance.
2. Using assert for Developer Sanity Checks vs. Input Validation
An `assert` statement acts as a conditional guard: Python evaluates the Boolean expression and does nothing when it is truthy, or raises `AssertionError` with the optional message when falsy. Because `assert total_items > 0, 'Cart cannot be empty'` reads cleanly, students sometimes confuse `assert` with `raise` for validating user-supplied data. In CBSE Class 12 CS (083), the distinction is explicit: use `assert` to catch programmer bugs and internal invariants during testing, and use `if ...: raise ...` for runtime validation of user or file inputs. The critical reason is that launching Python with optimization flags (`python -O script.py`) completely removes every `assert` statement from bytecode, disabling any security or input check written with `assert`. Never write parentheses like `assert(cond, msg)`, because Python treats a non-empty tuple as always `True`.
- `assert cond, msg` is roughly equivalent to `if __debug__ and not cond: raise AssertionError(msg)`.
- Avoid `assert` for production input validation because `python -O` skips assertions.
- Never wrap `assert` arguments in parentheses like a function call.
3. Designing Custom Exception Subclasses for Clean Error Handling
Built-in exceptions cover arithmetic and type failures well, yet domain rules—such as negative withdrawal amounts or marks exceeding 100—become much clearer when given dedicated exception names. Creating a custom exception requires inheriting from `Exception` (not `BaseException`, so callers using `except Exception:` can still catch it) with a minimal class body or custom attributes. Once defined, `class OutOfRangeMarksError(Exception): pass` lets callers catch domain failures separately from unexpected `ZeroDivisionError` or `FileNotFoundError` crashes. You can also attach structured context like `self.score = score` inside `__init__` while calling `super().__init__(message)` so the error prints informatively in tracebacks. Keeping custom exception classes lightweight and clearly named improves modularity in CBSE project files using CSV or binary `.dat` records.
- Inherit custom errors from `Exception`, never directly from `BaseException`.
- Use `super().__init__(msg)` if overriding `__init__` to preserve readable error text.
- Distinct custom names let callers separate business-rule errors from I/O errors.
4. Validating Inputs with raise, assert, and Custom Exceptions
class OutOfRangeError(Exception):
def __init__(self, value, message):
self.value = value
super().__init__(message)
def compute_percentage(scored, maximum):
assert isinstance(scored, (int, float)), "scored must be numeric"
if maximum == 0:
raise ZeroDivisionError("Maximum marks cannot be zero")
if scored < 0 or scored > maximum:
raise OutOfRangeError(scored, f"Score {scored} outside 0..{maximum}")
return round((scored / maximum) * 100, 2)
test_cases = [(45, 50), (40, 0), (55, 50), ("45", 50)]
for s, m in test_cases:
try:
pct = compute_percentage(s, m)
print("Percentage:", pct)
except (ZeroDivisionError, OutOfRangeError, AssertionError) as err:
print(type(err).__name__ + ":", err)
Verified Console / Dry-Run Output:
Percentage: 90.0
ZeroDivisionError: Maximum marks cannot be zero
OutOfRangeError: Score 55 outside 0..50
AssertionError: scored must be numeric
5. Comparison of Exception Raising Mechanisms in Python
| Mechanism | Exception Raised | Survives python -O? | Best CBSE Use Case |
|---|---|---|---|
| raise ZeroDivisionError(msg) | ZeroDivisionError | Yes | Guard against zero divisor before arithmetic |
| raise (bare, inside except) | Active exception re-thrown | Yes | Log locally and pass error up to caller |
| assert cond, msg | AssertionError | No (stripped) | Internal invariant and unit test checks |
| class CustomErr(Exception) | CustomErr | Yes | Domain rules like marks or age bounds |
Write Bulletproof Validation Code for Boards
Practice CBSE Class 12 CS 083 exception raising, assertions, and custom error handling at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 trial class.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Writing `assert(x > 0, 'bad')` with parentheses, which creates a 2-tuple that always evaluates to `True`.
- Avoid Mistake: Using `assert` to validate user or file input instead of an `if` check with `raise`.
- Avoid Mistake: Inheriting a custom exception directly from `BaseException` instead of `Exception`.
- Examiner / Mentor Tip: State the built-in exception hierarchy in viva: `BaseException` -> `Exception` -> `ArithmeticError` -> `ZeroDivisionError`.
- Examiner / Mentor Tip: When asked to differentiate `raise` and `assert`, highlight `python -O` optimization stripping `assert`.
- Examiner / Mentor Tip: Show how bare `raise` inside `except` re-throws the original exception without losing its traceback.
7. Interactive Concept Check Quiz
Question: What happens when Python executes: x = -5; assert (x > 0, 'x must be positive')?
8. Frequently Asked Questions
What is the difference between ZeroDivisionError and ValueError when raising manually?
Can a raise statement appear inside an except block with a different exception?
Is it mandatory to pass a message string to a custom Exception class?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in CBSE CS (083) & IP (065) Hub
- Python random Module Probable Output Questions: randint vs randrange (CBSE 083)
- Python String Slicing s[::-1] and Negative Index Outputs
- Python String split() vs partition() and find() vs index()
- Interactive Tool: CBSE CS 083 Python Output Predictor Quiz
- Interactive Tool: CBSE SQL GROUP BY / HAVING / JOIN Query Evaluator
