{"record":{"id":"2d87c014f6600186","repo":"Textualize/rich","slug":"value-for-trace-required-if-not-called-in-except","errorCode":null,"errorMessage":"Value for 'trace' required if not called in except: block","messagePattern":"Value for 'trace' required if not called in except: block","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"rich/traceback.py","lineNumber":318,"sourceCode":"        code_width: Optional[int] = 88,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n        locals_max_depth: Optional[int] = None,\n        locals_hide_dunder: bool = True,\n        locals_hide_sunder: bool = False,\n        locals_overlow: Optional[OverflowMethod] = None,\n        indent_guides: bool = True,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ):\n        if trace is None:\n            exc_type, exc_value, traceback = sys.exc_info()\n            if exc_type is None or exc_value is None or traceback is None:\n                raise ValueError(\n                    \"Value for 'trace' required if not called in except: block\"\n                )\n            trace = self.extract(\n                exc_type, exc_value, traceback, show_locals=show_locals\n            )\n        self.trace = trace\n        self.width = width\n        self.code_width = code_width\n        self.extra_lines = extra_lines\n        self.theme = Syntax.get_theme(theme or \"ansi_dark\")\n        self.word_wrap = word_wrap\n        self.show_locals = show_locals\n        self.indent_guides = indent_guides\n        self.locals_max_length = locals_max_length\n        self.locals_max_string = locals_max_string\n        self.locals_max_depth = locals_max_depth\n        self.locals_hide_dunder = locals_hide_dunder\n        self.locals_hide_sunder = locals_hide_sunder","sourceCodeStart":300,"sourceCodeEnd":336,"githubUrl":"https://github.com/Textualize/rich/blob/9d8f9a372cc5916fd4781fec207ced7ddac2f08f/rich/traceback.py#L300-L336","documentation":"Traceback's constructor accepts an optional trace= argument (pre-extracted StackTrace). When trace is None it falls back to sys.exc_info() to capture the in-flight exception; if there is no active exception (exc_type is None) it cannot build anything and raises ValueError('Value for \\\"trace\\\" required if not called in except: block').","triggerScenarios":"Constructing Traceback() at module level or in normal flow (no except: block active); saving a Traceback(...) factory call in a helper invoked outside the handler; calling Traceback(None) explicitly outside except. Inside except, or with trace= supplied, it works.","commonSituations":"Building a reusable 'format last error' utility that may be called when no exception is active; deferred rendering — creating Traceback in one function but raising/catching elsewhere; testing traceback rendering outside an exception context.","solutions":["Construct Traceback inside the except: block, or pass trace=Traceback.extract(*sys.exc_info()) captured earlier.","In helpers, guard with sys.exc_info()[0] is not None before constructing, else render a generic message.","Store exc_info at capture time: tb_info = sys.exc_info(); later Traceback(trace=Traceback.extract(*tb_info))."],"exampleFix":"# before\ndef fmt():\n    return Traceback()  # ValueError when no active exception\n\n# after\nimport sys\nfrom rich.traceback import Traceback\ndef fmt():\n    if sys.exc_info()[0] is None:\n        return Text('no active exception')\n    return Traceback(show_locals=True)","handlingStrategy":"validation","validationCode":"import sys\nfrom rich.traceback import Traceback\n\ndef current_traceback(**kw):\n    if sys.exc_info()[0] is None:\n        return None  # caller renders a fallback message\n    return Traceback(**kw)","typeGuard":null,"tryCatchPattern":"try:\n    tb = Traceback(show_locals=True)\nexcept ValueError:\n    tb = None  # not in an except block","preventionTips":["Construct Traceback inside the except: block, or pass trace=Traceback.extract(*sys.exc_info()) captured at raise time.","Guard helpers with sys.exc_info()[0] is not None before building a Traceback."],"tags":["rich","traceback","exception-context","valueerror","debugging"],"backgroundTag":null,"analyzedSha":"9d8f9a372cc5916fd4781fec207ced7ddac2f08f","analyzedAt":"2026-08-15T03:30:11.781Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}