Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python re Raise Exception: What Gets Raised and When

Understand when Python's re module raises re.error, how to read its attributes, and how to raise custom exceptions from regex callbacks.

~4 min readPython
#re module#re.error#exception handling#regex
Illustration of a Python regex pattern triggering an exception, shown as an alert symbol beside a pattern string.

When you pass an invalid pattern to Python's re module, the call does not return a sentinel value. Instead, the module raises re.error (also exposed as re.PatternError in Python 3.13) at the point where it tries to compile the pattern. This article covers exactly when re.error fires, when it does not, and how to raise your own exceptions from regex callbacks.

What the re Module Raises and When It Stays Silent

The re module raises re.error when a string pattern cannot be compiled and when re.sub or match.expand sees an invalid replacement template, such as a reference to a nonexistent group. A pattern with an unmatched parenthesis or an invalid escape is the most common trigger.

python
import re try: re.compile(r"[a-") except re.error as exc: print(exc.msg) # human-readable error message print(exc.pattern) # the original pattern print(exc.pos) # index where compilation failed

The exception is raised when the pattern is compiled, which happens either when you call re.compile explicitly or when you call a module-level function such as re.search or re.sub with a string pattern.

The re module does not raise an exception when a pattern simply fails to match. re.search returns None, re.match returns None, and re.sub returns the input string unchanged. This is a deliberate design choice, and it is the most common source of confusion for developers who expect a missing match to be an error. If a missing match must be treated as a failure, check the return value yourself and raise your own exception.

The re.error Exception Object and Its Attributes

re.error carries structured information about what went wrong. The msg attribute contains the human-readable message, and when the failure comes from pattern compilation, pattern, pos, lineno, and colno identify the offending pattern and its location.

python
import re try: re.compile(r"(?P<name>abc") except re.error as exc: print(exc.msg) # missing ), unterminated subpattern print(exc.pattern) # the original pattern print(exc.pos) # index where compilation failed

For errors raised while parsing a replacement template, pattern may refer to the replacement template rather than the search pattern. Attributes such as pos, lineno, and colno may be less meaningful or absent depending on how the error was raised, so treat them as optional diagnostic details rather than required fields.

Replacement-String Errors and Group References

re.sub validates group references in a string replacement and raises re.error if the replacement references a group that does not exist. The validation is part of the re.sub call; it does not depend on a match being found.

python
import re try: re.sub(r"(a)", r"\2", "abc") except re.error as exc: print(exc.msg) # invalid group reference 2

The same applies to match.expand and to re.sub with a named group reference such as \g<missing>. Note that match.group(99) behaves differently: it raises IndexError, not re.error, because the group number is out of range for the compiled pattern. This distinction matters when you write a single except clause, because catching re.error alone will not handle an out-of-range group access.

Catching re.error Without Swallowing Unrelated Failures

A focused except re.error is the right way to handle regex failures, because it leaves unrelated exceptions untouched. Catching a bare Exception around regex calls can hide bugs in callback functions or in surrounding code, especially when the regex operation runs inside a larger processing loop.

python
import re def parse_identifier(text): try: return re.match(r"[a-zA-Z_]\w*", text) except re.error: raise ValueError("invalid identifier pattern") from None

When a callback function passed to re.sub raises an exception, that exception propagates unchanged; re.sub does not wrap it in re.error. If you want a specific failure mode from inside the callback, raise the exception directly and let it escape.

Raising Exceptions From Regex Callback Functions

The replacement argument of re.sub can be a function. When that function raises, the exception propagates out of re.sub as-is, with the original traceback intact.

python
import re def replace(match): value = match.group(1) if not value.isdigit(): raise ValueError(f"expected digits, got {value!r}") return str(int(value) * 2) re.sub(r"(\d+)", replace, "12 34")

This is useful for validation pipelines where a malformed match should stop processing immediately rather than being silently replaced. The exception type you raise is entirely under your control; re.sub does not intercept or translate it.

Wrapping Regex Failures in Domain-Specific Exceptions

In larger codebases, leaking re.error into business logic couples callers to the re module's exception type. A common pattern is to catch re.error at the boundary and re-raise a domain exception with a clear message.

python
class ConfigParseError(Exception): pass def parse_config(pattern, text): try: return re.search(pattern, text) except re.error as exc: raise ConfigParseError(f"invalid config pattern: {exc.msg}") from exc

Using from exc preserves the original traceback, which helps when debugging the underlying pattern. This pattern keeps regex-specific details inside the parsing layer and gives callers a stable exception contract.

Writing Maintainable Regex Error Handling

Compiling patterns once and reusing the compiled object reduces repeated compilation work and makes error handling more predictable, because a malformed pattern fails fast at import or initialization time rather than in the middle of a request.

python
_PATTERN = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})") def extract_date(text): match = _PATTERN.search(text) if match is None: raise ValueError("date not found") return match.group("year"), match.group("month")

For compatibility, note that Python 3.13 added re.PatternError; re.error and re.PatternError refer to the same exception. Code that catches re.error continues to work on 3.13 and earlier. If you support versions before 3.13, catch or reference re.error.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.