all Python 3Exceptionsconstruct
raise
raising
Raises an exception by hand. raise ... from chains exceptions together. A bare raise re-raises the current one.
Syntax
raise ValueError('msg')
raise RuntimeError('msg') from original
A bare raise is legal only inside an exception handler (otherwise RuntimeError: No active exception to re-raise) and it preserves the original traceback — writing raise e instead just adds an extra stack frame. Inside except, Python already chains exceptions on its own ("During handling of the above exception, another exception occurred"); from states the cause explicitly, and from None hides the earlier exception from the report. You may raise either a class or an instance: raise ValueError and raise ValueError() are equivalent, the class gets instantiated for you.
Examples
def check_age(age):
if age < 0:
raise ValueError(f'Age cannot be negative: {age}')
return age
try:
check_age(-1)
except ValueError as e:
print(e) # → Age cannot be negative: -1
# raise from
try:
try:
int('abc')
except ValueError as e:
raise RuntimeError('conversion failed') from e
except RuntimeError as err:
print(type(err.__cause__).__name__) # → ValueError — исходная причина сохранена
# Re-raise
def safe():
try:
return 1/0
except ZeroDivisionError:
print('caught, re-raising')
raise # передаёт исходное исключение
try:
safe()
except ZeroDivisionError:
print('handled') # → caught / handled
# raise с кастомным классом
class ValidationError(ValueError):
pass
def validate(x):
if x < 0:
raise ValidationError(f'Invalid value: {x}')
try:
validate(-5)
except ValidationError as e:
print(e) # → Invalid value: -5
# raise без аргументов в except
try:
try:
1/0
except ZeroDivisionError:
raise # пробрасываем
except ZeroDivisionError:
print('outer caught') # → outer caught
# Цепочка __cause__ и __context__
try:
raise ValueError('first') from TypeError('cause')
except ValueError as e:
print(type(e.__cause__).__name__) # → TypeError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy