You have a two basic choices:
- Treat
handle_exceptions as a boolean, and re-raise if False - Treat
handle_exceptions as the exceptions to handle
Along the boolean route you have two basic choices:
def my_func(my_arg, handle_exceptions): try: do_something(my_arg) except Exception as e: if not handle_exceptions: raise print("my_func is handling the exception")
or
def my_func(my_arg, handle_exceptions): if handle_exceptions: exceptions = ValueError, IndexError # or whatever else: exceptions = NoExceptions # None in 2.x, or custom Exception class in 3.x try: do_something(my_arg) except exceptions as e: print("my_func is handling the exception")
Along the 'treat handle_exceptions as the exceptions to handle' route you can do this:
class NoExceptions(Exception): 'Dummy exception, never raised' def my_func(my_arg, handle_exceptions=NoExceptions): try: do_something(my_arg) except handle_exceptions as e: print("my_func is handling the exception")
and you would call it like so:
my_func(some_arg, ValueError) # to handle ValueErrors
or
my_func(some_arg) # to not handle any exeptions
This has the advantage/disadvantage of the caller being able to specify which exceptions are handled. If you do take this last route you might also want to specify an exception handler, perhaps something like this:
def my_func(my_arg, handle_exceptions=NoExceptions, handler=None): try: do_something(my_arg) except handle_exceptions as e: if handler is not None: handler(e) else: log_this_exception()