0
0
PythonHow-ToBeginner · 3 min read

How to Raise Exception in Python: Syntax and Examples

In Python, you raise an exception using the raise keyword followed by an exception instance or class. This interrupts normal program flow and signals an error or special condition.
📐

Syntax

The basic syntax to raise an exception is:

  • raise ExceptionType("message"): Raises a new exception of the specified type with an optional message.
  • raise: Re-raises the last caught exception inside an except block.

This tells Python to stop normal execution and jump to error handling.

python
raise ExceptionType("Error message")
💻

Example

This example shows how to raise a ValueError if a number is negative:

python
def check_positive(number):
    if number < 0:
        raise ValueError("Number must be positive")
    return number

try:
    check_positive(-5)
except ValueError as e:
    print(f"Caught an error: {e}")
Output
Caught an error: Number must be positive
⚠️

Common Pitfalls

Common mistakes when raising exceptions include:

  • Using raise outside an except block without specifying an exception causes an error.
  • Raising exceptions without a message can make debugging harder.
  • Raising the wrong exception type for the error can confuse users.
python
try:
    raise
except RuntimeError as e:
    print(f"Error: {e}")

# Correct way:
try:
    raise ValueError("Invalid input")
except ValueError as e:
    print(f"Caught: {e}")
Output
Traceback (most recent call last): File "<stdin>", line 2, in <module> RuntimeError: No active exception to reraise Caught: Invalid input
📊

Quick Reference

UsageDescription
raise ExceptionType("message")Raise a new exception with a message
raiseRe-raise the last caught exception inside except block
raise ExceptionTypeRaise an exception without a message

Key Takeaways

Use raise ExceptionType("message") to signal errors clearly.
Always provide a helpful message to make debugging easier.
Use raise alone only inside an except block to re-raise exceptions.
Choose the right exception type to match the error condition.
Avoid raising exceptions without context or outside error handling blocks.