Exception.args holds the arguments passed to the exception. You could add type checking with dataclass, or you can just access Exception.args or sys.exc_info().args:
```python class Exception2(Exception): pass try: raise Exception2('error str', dict(a='1', b=2)) except Exception2 as e: print(('args', e.args)) assert e.args[0] == 'error str' assert e.args[1] == dict(a='1', b=2) import sys type_, value, traceback = sys.exc_info() assert value.args[0] == 'error str' assert value.args[1] == dict(a='1', b=2) # ('args', ('error str', {'a': '1', 'b': 2})) ``` On Tue, Oct 13, 2020 at 12:56 PM David Mertz <me...@gnosis.cx> wrote: > On Tue, Oct 13, 2020 at 6:18 AM Steven D'Aprano <st...@pearwood.info> > wrote: > >> I don't think that a two line class (perhaps a couple of extra >> lines if you give it a docstring) justifies the name "boilerplate": >> >> class MySpecialException(Exception): >> pass >> > > I think that in 22 years of using Python, I have never written an > exception that took more than these two lines of code. > > Heck, I even have my memory jogged of string exceptions reading this. > When did those go away fully, 1.5.2? 2.1? > > I DID in the discussion, immediately think of making an exception a > dataclass, as someone else replied with. I guess if you want cargo in your > exception, that's a pretty good way to do it. But really the ONLY thing I > ever want in an exception is an inheritance tree. An exception feels like > a really unnatural way to pass around data (that said, there are a few > exceptions written by other libraries where some attribute or another is > useful in my except blocks. Perhaps I should consider that, beyond > inspecting the traceback when needed. > > If you really want a snazzy highly-parameterized exception, write it > yourself as a class factory. I won't particularly like the antipattern, > but it's available now. > > if some_bad_thing: > raise ExceptionMaker("BadStuffErrror", details, plus, more_details) > > Implementation of 'ExceptionMaker' left to readers. But it's possible to > write once. > > > _______________________________________________ > Python-ideas mailing list -- python-ideas@python.org > To unsubscribe send an email to python-ideas-le...@python.org > https://mail.python.org/mailman3/lists/python-ideas.python.org/ > Message archived at > https://mail.python.org/archives/list/python-ideas@python.org/message/M7LP4OMSEU47MBWX75KGBM7343SH5XGI/ > Code of Conduct: http://python.org/psf/codeofconduct/ >
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/INKNKKYLUTMHTYMW2OTSFIIEV335IIJP/ Code of Conduct: http://python.org/psf/codeofconduct/