Why should applications define their own exception classes, and what does `raise NewError(...) from original_error` add?
Answer
Custom exception classes let calling code catch and react to specific domain failures (`InsufficientFundsError`) instead of generic ones (`ValueError`), and they can carry structured data about the failure as attributes rather than only a formatted message string. Even a bare `raise NewError(...)` inside an `except` block does not normally lose the original exception — Python automatically records it as `__context__` and still shows it in the traceback with a "During handling of the above exception, another exception occurred" note. `raise NewError(...) from original_error` goes further: it explicitly promotes that relationship to a deliberate `__cause__`, producing a traceback with the clearer "The above exception was the direct cause of the following exception" wording, and `from None` is the way to suppress the original entirely on the rare occasions that is genuinely intended.
Strong answer includes
- custom exceptions let callers react to specific domain failures
- can carry structured data, not just a message string
- a bare raise inside except still keeps the original as __context__; raise ... from promotes it to an explicit __cause__
Practical example
Run the code to see the result.
Callers can catch the domain-specific ConfigMissingError, while `from exc` keeps the original KeyError as an explicit cause in the traceback.
Expected result: ConfigMissingError is raised, with KeyError('token') shown as its direct cause.