RuntimeError, or user defined exception
Cameron Simpson
cs at cskk.id.au
Sat Feb 5 00:04:24 EST 2022
On 04Feb2022 21:39, Cecil Westerhof <Cecil at decebal.nl> wrote:
>I am creating a class that will call a user defined function on user
>defined intervals. In my opinion it is an error when the function
>takes more as 10% of interval, or more as half a second. What is
>better: just using RuntimeError, or creating two exception classes for
>this?
You could reuse TimeoutError, a builtin exception raised by OS calls
which time out: https://docs.python.org/3/library/exceptions.html#TimeoutError
I wouldn't use RuntimeError. Its core purpose is interpreter failures
IIRC, and I use it myself for situations which should never occur -
things indicating an actual bug in my code.
Specificly, I do not expect to try to catch RuntimeError, and broadly
don't expect anything else too either (with some narrow exceptions).
Whereas you would very reasonably catch TimeoutError as a situation
which can readily occur. _Particularly_ with a tool which runs code
supplied from outside - it _might_ do anything.
IMO your situation is a misbehaviour, not an internal bug. I'd reach for
TimeoutError.
An example from my own code where I use a RuntimeError:
class FSTagsCommand(BaseCommand, TagsCommandMixin):
''' `fstags` main command line utility.
'''
GETOPT_SPEC = 'o:'
[.......]
def apply_opt(self, opt, val):
''' Apply command line option.
'''
options = self.options
if opt == '-o':
options.ontology_path = val
else:
raise RuntimeError("unhandled option")
Here, the BaseCommand superclass parses command line options according
to GETOPT_SPEC. The apply_opt() method gets called with any valid
options. GETOPT_SPEC='o:', so seeing anything except '-o' in apply_opt()
indicates a mismatch between GETOPT_SPEC and my apply_opt implementation
(other options get rejected by BaseCommand). So _if_ my code gets there,
that is an internal bug of my own.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list