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):
?methodB
twice. Depending on what these functions do, this might be OK, but it also might be a bug.