A simplified version of my code looks like this:
def process( object ):
try:
if suitedForA( object ):
try:
methodA( object )
except:
methodB( object )
else:
# we would get a bad result from methodA()
methodB( object )
except:
methodC( object )
Edit: Removed error in pseudo code pointed out by @gnasher729.
I would like to avoid the repetition of methodB()
. It may look not as bad in above pseudo-code, but in actuality, these are library calls with a bit of post-processing.
Edit: methodA/B/C()
may fail without me being able to tell when. This is independent of suitedForA()
.
The following code avoids the repetition, but I am not sure if it is a good idea to throw an exception for this case:
def process( object ):
try:
if not suitedForA( object ):
raise NotSuitedException()
methodA( object )
except:
try:
methodB( object )
except:
methodC( object )
Is there a simpler approach to achieve the same without the repetition and without actively throwing an exception?
methodB(object)
throw an exception? If it can, you may end up calling it twice in your first function, but only once in your second function. Maybe your try/except should be inside theif suitedForA(object):
? – Kevin Dec 13 '22 at 14:57methodB
twice. Depending on what these functions do, this might be OK, but it also might be a bug. – Greg Burghardt Dec 13 '22 at 15:36suitedForA
then checksuitedForB/C/D
etc and just error on exceptions. – Ewan Dec 13 '22 at 18:51suitedForA()
is independent of whethermethodA()
will fail.methodA/B/C()
are library functions that sometimes fail without me being able to tell when. – Jann Poppinga Dec 14 '22 at 07:19methodA()
cannot be used. – Jann Poppinga Dec 15 '22 at 10:15suitedForA
should never throw an expected exception when passed intomethodA
. It may be an issue of verbiage more than anything else, but I would not expect adisc
object that passesisDvd
but throws an exception inreadDvd
to then be an eligible candidate forreadBluRay
, just to give an example. – Michael Brandon Morris Dec 20 '22 at 01:47suitedForA
represent something likesuitedForFlying
or more likesuitedForRotarWing
? – Marcel Wilson Dec 22 '22 at 19:59except KeyError
– JimmyJames Jan 31 '23 at 22:23std::exception
). I'm down for discussing different philosophies and outlooks though! It's just, at least from my perspective and there could very well be a bias there, I think it degrades the productivity of exceptions to have to write a lot of exception-handling code catching things very specifically that often fit into regular and expected control flow likeKeyError
. – Anti Gamer Jan 31 '23 at 22:23