Python - Conditionally Catching Exceptions?

You can re-raise the exception if you don't want to handle it: def my_func(my_arg, handle_exceptions): try: do_something(my_arg) except Exception, e: if not handle_exceptions: # preserve prior stack trace raise # Or, if you don't care about the stack prior to this point #raise Exception(e) # similarly, you can just re-raise e. The stack trace will start here though. #raise e else: print "my_func is handling the exception Another option is to create your own exceptions that subclass Exception (or a specific exception like urllib2.

HTTPError ) and then only catch/throw (raise) your specific custom exception: class MyException(Exception): def __init__(self, message): self. Message = message class MyExceptionTwo(Exception): def __init__(self, message): self. Message = message def __repr__(self): return " I'm MyExceptionTwo.My error message is: %s" % self.

Message def something(): if not tuesday: raise MyException("Error: it's not Tuesday. ") else: raise MyExceptionTwo("Error: it's Tuesday.") def my_func(my_arg): try: something() except MyException, e: print e. Message # Will pass MyExceptionTwo up the call chain def my_other_func(): try: my_func(your_arg) except MyExceptionTwo, e: print str(e) # No need to catch MyException here since we know my_func() handles it # but we can hadle MyExceptionTwo here.

You can re-raise the exception if you don't want to handle it: def my_func(my_arg, handle_exceptions): try: do_something(my_arg) except Exception, e: if not handle_exceptions: # preserve prior stack trace raise # Or, if you don't care about the stack prior to this point #raise Exception(e) # similarly, you can just re-raise e. The stack trace will start here though. #raise e else: print "my_func is handling the exception" Another option is to create your own exceptions that subclass Exception (or a specific exception like urllib2.

HTTPError) and then only catch/throw (raise) your specific custom exception: class MyException(Exception): def __init__(self, message): self. Message = message class MyExceptionTwo(Exception): def __init__(self, message): self. Message = message def __repr__(self): return " I'm MyExceptionTwo.My error message is: %s" % self.

Message def something(): if not tuesday: raise MyException("Error: it's not Tuesday. ") else: raise MyExceptionTwo("Error: it's Tuesday.") def my_func(my_arg): try: something() except MyException, e: print e. Message # Will pass MyExceptionTwo up the call chain def my_other_func(): try: my_func(your_arg) except MyExceptionTwo, e: print str(e) # No need to catch MyException here since we know my_func() handles it # but we can hadle MyExceptionTwo here.

– speedplane Nov 16 at 3:45 3 @speedplane If you just use raise, the stack will stay in-tact. If you raise e or raise Exception(e) it will start the stack trace at the point where you raised it. – chown Nov 16 at 3:55.

You can use: 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.

The exception type can be a variable. Def my_func(my_arg, handle_exceptions): if handle_exceptions: exc_type = Exception else: exc_type = None try: do_something(my_arg); except exc_type, e: print "my_func is handling the exception"; Obfuscated Python ("Pythonic"? ) version: def my_func(my_arg, handle_exceptions): try: do_something(my_arg); except (handle_exceptions and Exception), e: print "my_func is handling the exception"; Works without the parentheses, actually, but as long as we're being obfuscated let's not confuse people with little known rules like precedence for except statements.

Except None will not work in Python 3. X – Ethan Furman Nov 16 at 16:30.

You could always catch it and conditionally re-raise it like so: def my_func(my_arg, handle_exceptions): try: do_something(my_arg) except Exception: if handle_exceptions: print "my_func is handling the exception" #handle it else: print "my_func is NOT handling the exception" raise.

Yes. I prefer positive conditions when it makes sense: def my_func(my_arg, handle_exceptions): try: do_something(my_arg); except Exception, e: if handle_exceptions: print "my_func is handling the exception" else: raise.

The question just doesn't have enough answers ;-) Here's one more for the record books. Just create a dummy exception: class NeverMatch(Exception): 'An exception class that is never raised by any code anywhere' Then, use a conditional expression to decide whether to match the real exception or the placeholder exception (which never gets raised): try: do_something(my_arg) except (Exception if handle_exceptions else NeverMatch) as e: print 'I am handling it.

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, 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, 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, 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, e: if handler is not None: handler(e) else: log_this_exception().

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions