all Python 3Exceptionsexception
UserWarning
built-in exceptions
The default category for warnings.warn().
Syntax
raise UserWarning
A common trap: warnings.warn('...') raises nothing — the text goes to stderr and execution continues, so an except UserWarning around the call catches nothing. To make warnings behave like real exceptions you need a filter: warnings.simplefilter('error') or running python -W error. Also, by default a warning from a given source line is printed only the first time it fires, so inside a loop it is easy to miss.
Examples
try:
raise UserWarning
except UserWarning as e:
print(type(e).__name__) # → UserWarning
See also
Open in the full glossarydocs.python.orgReport an inaccuracy