1

For example:

class ExceptionMeta(type):
  def __call__(cls, *args, **kwargs):
    if exception_raised_from_try_block:
       do_something
    else:
       do_something_else

class TimeOutError(metaclass = ExceptionMeta):
  pass

try:
  raise TimeOutError
except Exception as e:
  pass

The actual problem is that I have a code block in which I am having a TimeOut error in the try - except block. Every time a TimeOut error is raised, I catch it in try - except block and issue retry for 5 times. This TimeOut error has an object which will collect the error traces in case the exception is raised so as to provide more context while debugging the issue. But every time the exception is raised in the try block, the call goes to call function and it ends up collecting the traces for that error which I dont want as I am just retrying again in the except block

Is there any way in python using inspection or some other module which can tell me that exception was raised from a try block?

12
  • 3
    what do you think happens in the except? Commented May 13, 2016 at 14:28
  • 3
    It seems like you are trying to filter out potentially uncaught exceptions. Is that correct? Can you explain further why you want to do that? Commented May 13, 2016 at 14:33
  • 3
    Looks like you want your exception to have a behavior if it is caught by a try block and another behavior if uncaught, but they are only a signal - exceptions should not have side effects. Commented May 13, 2016 at 14:33
  • 1
    but why do you need such strange feature? Describe functionality you are trying fulfill, I've got feeling that this can be solved without this crazy concept. Commented May 13, 2016 at 14:36
  • 2
    Welcome to stackoverflow. Looks like the question suffers from the A/B problem: @user2819403 has problem A, but instead of asking about problem A he is asking about his devised solution B. Please edit your question to show the original problem. The solution you are trying to implement is not idiomatic in Python. Commented May 13, 2016 at 14:38

1 Answer 1

1

So your problem is retrying a block of code...

Suppose you have some code like:

import random

def do_something_unreliable(msg="we have landed"):
    if random.randint(0, 10) > 1:
        raise Exception("Timed out...")
    else:
        return "Houston, {0}.".format(msg)

You can retry 5 times by doing:

for attempt in range(1, 5):
    try:
        do_something_unreliable()
    except Exception:
        # print("timeout, trying again...")
        pass
    else:
        break
else:
    do_something_unreliable()

You can make it reusable by doing:

def retry(fn, args=None, kwargs=None, times=5, verbose=False, exceptions=None):
    if args is None:
        args = []
    if kwargs is None:
        kwargs = {}
    if exceptions is None:
        exceptions = (Exception,)
    for attempt in range(1, times):
        try:
            return fn(*args, **kwargs)
        except exceptions as e:
            if verbose:
                print("Got exception {0}({1}), retrying...".format(
                         e.__class__.__name__, e))
    return fn(*args, **kwargs)

Then you can write:

>>> retry(do_something_unreliable, verbose=True)
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
'Houston, we have landed.'

>>> retry(do_something_unreliable, ['we are lucky'], verbose=True)
Got exception Exception(Timed out...), retrying...
Got exception Exception(Timed out...), retrying...
'Houston, we are lucky.'

You can also take a look at the retrying decorator:

Retrying is an Apache 2.0 licensed general-purpose retrying library, written in Python, to simplify the task of adding retry behavior to just about anything.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.