{"record":{"id":"8a3ca6facf5608bd","repo":"pytest-dev/pytest","slug":"expected-expected-but-got-an-exception-instance","errorCode":null,"errorMessage":"Expected {expected}, but got an exception instance: {type(exc).__name__}","messagePattern":"Expected (.+?), but got an exception instance: (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/_pytest/raises.py","lineNumber":453,"sourceCode":"                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\n        test failing.\"\"\"\n        return self._fail_reason\n\n    def _check_check(\n        self: AbstractRaises[BaseExcT_1],\n        exception: BaseExcT_1,\n    ) -> bool:\n        if self.check is None:\n            return True\n\n        if self.check(exception):\n            return True","sourceCodeStart":435,"sourceCodeEnd":471,"githubUrl":"https://github.com/pytest-dev/pytest/blob/0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc/src/_pytest/raises.py#L435-L471","documentation":"Raised by RaisesExc._parse_exc when an exception INSTANCE is passed where a TYPE is expected. pytest.raises/RaisesExc accept classes (or group generics), not instances like ValueError('x'). The TypeError reports the actual instance type so the caller sees the mismatch.","triggerScenarios":"pytest.raises(ValueError('boom')), RaisesExc(RuntimeError('x')), or passing excinfo.value (an instance) instead of type(excinfo.value). Fires on the isinstance(exc, BaseException) branch after the type branch.","commonSituations":"Copy-paste from a raise ValueError('x') line into raises(...); passing a caught exception instance through a variable; beginners assuming raises mirrors raise syntax.","solutions":["Pass the class: pytest.raises(ValueError) instead of pytest.raises(ValueError('boom')).","If asserting on message, use the match= argument: pytest.raises(ValueError, match='boom').","When the value comes from excinfo, use type(excinfo.value)."],"exampleFix":"// before\nwith pytest.raises(ValueError('boom')):\n    ...\n// after\nwith pytest.raises(ValueError, match='boom'):\n    ...","handlingStrategy":"type-guard","validationCode":"assert not isinstance(exc, BaseException), f'pass the exception class, not an instance: {type(exc).__name__}'","typeGuard":"def is_exception_class_not_instance(exc) -> bool:\n    return isinstance(exc, type) and not isinstance(exc, BaseException)","tryCatchPattern":null,"preventionTips":["Pass classes (ValueError), not instances (ValueError('x')), to raises.","Use match= to assert on the message rather than constructing an instance.","When forwarding from excinfo, use type(excinfo.value)."],"tags":["pytest","raises","type-instance-mismatch","misuse"],"backgroundTag":null,"analyzedSha":"0d6fbdeffa57c796123f62f81f7dd370d9b7ecdc","analyzedAt":"2026-08-11T20:52:36.969Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}