{"id":"be424c7d64acc5bb","repo":"pytest-dev/pytest","slug":"only-exceptiongroup-exception-or-baseexception","errorCode":null,"errorMessage":"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` are accepted as generic types but got `{exc}`. As `raises` will catch all instances of the specified group regardless of the generic argument specific nested exceptions has to be checked with `RaisesGroup`.","messagePattern":"Only `ExceptionGroup\\[Exception\\]` or `BaseExceptionGroup\\[BaseException\\]` are accepted as generic types but got `(.+?)`\\. As `raises` will catch all instances of the specified group regardless of the generic argument specific nested exceptions has to be checked with `RaisesGroup`\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/_pytest/raises.py","lineNumber":441,"sourceCode":"            if not issubclass(exc, Exception):\n                self.is_baseexception = True\n            return exc\n        # because RaisesGroup does not support variable number of exceptions there's\n        # still a use for RaisesExc(ExceptionGroup[Exception]).\n        origin_exc: type[BaseException] | None = get_origin(exc)\n        if origin_exc and issubclass(origin_exc, BaseExceptionGroup):\n            exc_type = get_args(exc)[0]\n            if (\n                issubclass(origin_exc, ExceptionGroup) and exc_type in (Exception, Any)\n            ) or (\n                issubclass(origin_exc, BaseExceptionGroup)\n                and exc_type in (BaseException, Any)\n            ):\n                if not issubclass(origin_exc, ExceptionGroup):\n                    self.is_baseexception = True\n                return cast(type[BaseExcT_1], origin_exc)\n            else:\n                raise ValueError(\n                    f\"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` \"\n                    f\"are accepted as generic types but got `{exc}`. \"\n                    f\"As `raises` will catch all instances of the specified group regardless of the \"\n                    f\"generic argument specific nested exceptions has to be checked \"\n                    f\"with `RaisesGroup`.\"\n                )\n        # unclear if the Type/ValueError distinction is even helpful here\n        msg = f\"Expected {expected}, but got \"\n        if isinstance(exc, type):  # type: ignore[unreachable]\n            raise ValueError(msg + f\"{exc.__name__!r}\")\n        if isinstance(exc, BaseException):  # type: ignore[unreachable]\n            raise TypeError(msg + f\"an exception instance: {type(exc).__name__}\")\n        raise TypeError(msg + repr(type(exc).__name__))\n\n    @property\n    def fail_reason(self) -> str | None:\n        \"\"\"Set after a call to :meth:`matches` to give a human-readable reason for why the match failed.\n        When used as a context manager the string will be printed as the reason for the","sourceCodeStart":423,"sourceCodeEnd":459,"githubUrl":"https://github.com/pytest-dev/pytest/blob/98b357f69e380da908740a212288d73b2ee06687/src/_pytest/raises.py#L423-L459","documentation":"Raised when a parameterized exception-group generic type is passed whose nested type argument is restricted. pytest.raises only accepts ExceptionGroup[Exception] or BaseExceptionGroup[BaseException] as generic forms because raises catches all instances of the group class regardless of the type parameter — specific nested types must be checked via RaisesGroup.","triggerScenarios":"Calling pytest.raises(ExceptionGroup[ValueError]) or RaisesExc(ExceptionGroup[TypeError]). Hits the else branch at raises.py:441 when get_origin returns a BaseExceptionGroup subclass but get_args()[0] is not Exception/BaseException/Any.","commonSituations":"Developer assumes the generic parameter filters nested exception types (it does not); migrating from except* syntax expecting per-type narrowing; copy-paste from type annotations into raises.","solutions":["Use pytest.RaisesGroup(ValueError) to assert specific nested exception types within the group.","If you truly want to catch any group regardless of contents, use the bare ExceptionGroup[Exception] or BaseExceptionGroup[BaseException] generic.","For 'one of several nested types', use RaisesGroup(RaisesExc(check=lambda e: isinstance(e, (ValueError, TypeError))))."],"exampleFix":"// before\nwith pytest.raises(ExceptionGroup[ValueError]):\n    raise ExceptionGroup('', [ValueError()])\n// after\nwith pytest.RaisesGroup(ValueError):\n    raise ExceptionGroup('', [ValueError()])","handlingStrategy":"validation","validationCode":"from typing import get_origin, get_args\nimport sys\nif sys.version_info >= (3, 11):\n    o = get_origin(expected_exception)\n    if o and issubclass(o, BaseExceptionGroup):\n        a = get_args(expected_exception)[0]\n        if a not in (Exception, BaseException) and a is not Any:\n            # use RaisesGroup instead\n            ...","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Use pytest.RaisesGroup(NestedType) when you care about nested exception types.","Only use ExceptionGroup[Exception] / BaseExceptionGroup[BaseException] bare generics with raises.","Remember the generic parameter on raises does NOT filter nested types — it is informational only."],"tags":["pytest","raises","exception-group","validation"],"analyzedSha":"98b357f69e380da908740a212288d73b2ee06687","analyzedAt":"2026-08-04T20:26:34.442Z","schemaVersion":2}