raise
KeywordPython 2.0+Beginner
Throws an exception manually
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.0+
Learn by Difficulty
Quick Example
python
def divide(a, b): if b == 0: raise ZeroDivisionError("Cannot divide by zero") return a / b try: result = divide(10, 0) except ZeroDivisionError as e: print(f"Error: {e}") # Raise with a message def validate_age(age): if not isinstance(age, int): raise TypeError("Age must be an integer") if age < 0 or age > 150: raise ValueError(f"Age {age} is out of range") return age try: validate_age(-5) except ValueError as e: print(f"Validation: {e}")
raise creates and throws an exception. Always include a descriptive message to help with debugging.
Try in PlaygroundTags
languagesyntaxcoreerror-handlingexception
Related Items
try
Keyword
Starts a block of code that will be monitored for exceptions
except
Keyword
Catches and handles exceptions raised in a try block
Exception
Built-in Exception
Base class for all non-exit exceptions; used to define custom exceptions
from
Keyword
Used with import to bring in specific names from a module
traceback
Stdlib — Testing
Print and format stack traces for exceptions