On 23/07/2019 04.27, DL Neil wrote: > On 23/07/19 11:00 AM, Ethan Furman wrote: >> On 07/20/2019 05:02 PM, DL Neil wrote: >> >>> Upon closer inspection, I realised it didn't just fail; it failed >>> badly! Some silly, little, boy had imported the PythonEnvironment >>> class but failed to ALSO import PythonVersionError. So, the reported >>> error was not the expected exception! >> >> I don't understand the significance of not importing PythonVersionError: >> >> - PythonEnvironment does not need it to be imported >> >> - when PythonEnvironment raises PythonVersionError you still get >> PythonVersionError >> >> - if your code says `except PythonVersionError` and you haven't >> imported it you'll get a NameError >> Actually, if your code says ‘except PythonVersionError’ this will only raise a NameError if there is an actual exception.
(this was not what I expected - I learned something new today!) If no exception is being handled, the except statements are never examined. This makes this harder to spot than you might think! % cat test.py try: print('ok') except FakeError: print('ah shit') % python3 test.py ok That makes me think... def get_exc(exc): print("we're checking for exception", exc) return exc try: print("raising no. 1") raise ValueError except get_exc(TypeError): print("t'was a TypeError") except get_exc(ValueError): print("t'was a ValueError") try: print("raising no. 2") raise TypeError except get_exc(TypeError): print("t'was a TypeError") except get_exc(ValueError): print("t'was a ValueError") >> So, what's the issue? > > > Have I correctly understood the question? > > NameError conveys nothing to the user. > PythonVersionError is more communicative - and speaks volumes to 'us'. > > The mainline code is something like: > > p = PythonEnvironment() > try: > p.compatibility( ...spec... ) # eg must be Py3 not 2.n > except PythonVersionError: > print( more illuminating errmsg ) > > If I am 'the user' I'd be quite happy without the try...except; but > mere mortals need/deserve something more. Accordingly, the > PythonVersionError custom exception/class. > > Yes, we could trap NameError, but that might also catch other > name-errors (unlikely in this example, but 'just sayin'). Thus the > greater specificity of the custom class. > > > NB please see alternative 'solution' proposed (for critique) as > "Nesting Custom Errors in Classes" discussion topic. -- https://mail.python.org/mailman/listinfo/python-list