Search code examples
pythonerror-handlingtry-catchexcepthardcode

Is there a way to write the same try-except for multiple lines of code without hardcoding? python


I have multiple functions that might return None:

do_something(), do_something2(), do_something3(), etc.

And to overcome the None Type Errors, from another part of the code I have to hardcode the try-except as such:

try:
  x = do_other_things(do_something())
except someError: # because of None Type return
  x = None

try:
  y = do_other_things(do_something2())
except someError: # because of None Type return
  y = None

Is there any way to just apply the same try-except to different lines of code/different function call?


Solution

  • If you are testing for the same exception type, then you can wrap the try/except block into a function that accepts as parameters other function and a list of parameters.

     def try_except(myFunction, *params):
         try:
             return myFunction(*params)
         except ValueError as e:
             return None
         except TypeError as e:
             return None