by sslnx · 7y ago · 0 comments
try as method1:
method1()
except@method1 try as method2:
method2()
except@method2 try as method3:
method3()
except@method3:
raise NoMethodWorked() methods = [method1, method2, method3, method4]
for method in methods:
try:
method()
except Exception:
pass
else:
break
else:
raise NoMethodWorked()
You can even pair specific exceptions to each method: methods = [(method1, TypeError), (method2, KeyError)]
for m, e in methods:
try: m()
except e: ...
But the whole thing really sounds like you're trying to do too much with one function and you really should rethink the whole structure of your code. try:
method1()
return
except Exception: # or a more specific exception type
pass # try the next method
try:
method2()
return
except Exception:
pass
# ...
try:
method10()
except Exception:
raise NoMethodWorked()
Seriously, there are so many ways to solve this in a readable, maintainable way, without resorting to introducing weird new syntax. try:
DispatchController.dispatch()
except:
raise DispatchFailed()
And/or use a lookup table. Especially since methods, classes, decorators, etc are all first class citizens in Python.