[Tutor] please return flys in ointment

Steven D'Aprano steve at pearwood.info
Tue Jul 9 03:16:17 CEST 2013


On 09/07/13 05:47, Dave Angel wrote:
> On 07/08/2013 01:57 PM, Jim Mooney wrote:
>> On 8 July 2013 00:12, Steven D'Apranocatching ArithmeticError
>>
>>> further on), please use a custom exception
>>>
>>
>> Well, an Arithmetic Error was better than bubbling up to a totally general
>> one. I'm not sure how do custom error code. Short example, please ;')
>>
>> Jim
>>
>
> I think a ValueError might be best.
[...]
> class TooHugeError (ValueError):
>     pass

I would normally agree, but in Jim's code the exception is purely being used for internal flow control, it is not being exposed to the caller. So I wouldn't inherit from ValueError, I'd keep this a completely independent exception. I wouldn't even call it an Error, since it's actually a limitation of Jim's code, not an actual error.

Also, since Jim's code already catches ValueError, he would need ensure that he catches this *first*, otherwise it will be caught by the ValueError handler:

try:
     raise TooHugeError
except TooHugeError:  # this must come first
     ...
except ValueError:  # otherwise this will catch it
     ...


Whereas if you keep the custom exception independent, the order of except clauses doesn't matter.


class TooHuge(Exception):
     pass


try:
     raise TooHuge
except ValueError:
     print("bad value")
except TooHuge:
     print("caught it")




-- 
Steven


More information about the Tutor mailing list