Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9234219
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T06:44:20+00:00 2026-06-18T06:44:20+00:00

I am creating a decorator that catches a raised error in it’s target function,

  • 0

I am creating a decorator that catches a raised error in it’s target function, and allows the user to continue executing the script (bypassing the function) or drop out of the script.

def catch_error(func):
    """
    This decorator is used to make sure that if a decorated function breaks 
    in the execution of a script, the script doesn't automatically crash. 
    Instead, it gives you the choice to continue or gracefully exit.    

    """
    def caught(*args):
        try:
            return func(*args)
        except Exception as err:
            question = '\n{0} failed. Continue? (yes/no): '.format(func.func_name)
            answer = raw_input(question)
            if answer.lower() in ['yes','y']:
                pass
            else:
                print "   Aborting! Error that caused failure:\n"
                raise err 
            return None
    return caught

Notice that, if the user chooses to bypass the error-returning function and continue executing the script, the decorator returns None. This works well for functions that only return a single value, but it is crashing on functions that attempt to unpack multiple values. For instance,

# Both function and decorator return single value, so works fine
one_val = decorator_works_for_this_func() 
# Function nominally returns two values, but decorator only one, so this breaks script
one_val, two_val = decorator_doesnt_work_for_this_func()

Is there a way that I can determine the number of values my target function is supposed to return? For instance, something like:

def better_catch_error(func):
    def caught(*args):
        try:
            return func(*args)
        except Exception as err:
            ...
            num_rvals = determine_num_rvals(func)
            if num_rvals > 1:
                return [ None for count in range(num_rvals) ]
            else:
                return None               
    return caught

As always, if there is a better way to do this sort of thing, please let me know. Thanks!

UPDATE:

Thanks for all the suggestions. I decided to narrow the scope of catch_error to a single class of functions, which only return one string value. I just split all the functions returning more than one value into separate functions that return a single value to make them compatible. I had been hoping to make catch_error more generic (and there were several helpful suggestions on how to do that), but for my application it was a little overkill. Thanks again.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T06:44:21+00:00Added an answer on June 18, 2026 at 6:44 am

    Martijn Pieters answer is correct, this is a specific case of the Halting Problem

    However you might get around it by passing a error return value to the decorator. Something like this:

    def catch_error(err_val):
        def wrapper(func):
            def caught(*args):
                try:
                    return func(*args)
                except Exception as err:
                    question = '\n{0} failed. Continue? (yes/no): '.format(func.func_name)
                    answer = raw_input(question)
                    if answer.lower() in ['yes','y']:
                        pass
                    else:
                        print "   Aborting! Error that caused failure:\n"
                        raise err 
                    return err_val
            return caught
        return wrapper
    

    Then you could decorate using:

    @catch_error({})
    def returns_a_dict(*args, **kwargs):
        return {'a': 'foo', 'b': 'bar'}
    

    Also as a point of style, if you are grabbing *args in your wrapped function, you should probably also grab **kwargs so that you can properly wrap functions that take keyword arguments. Otherwise your wrapped function will fail if you call wrapped_function(something=value)

    Finally, as another point of style, it is confusing to see code that does if a: pass with an else. Try using if !a in these cases. So the final code:

    def catch_error(err_val):
        def wrapper(func):
            def caught(*args, **kwargs):
                try:
                    return func(*args, **kwargs)
                except Exception as err:
                    question = '\n{0} failed. Continue? (yes/no): '.format(func.func_name)
                    answer = raw_input(question)
                    if answer.lower() not in ['yes','y']:
                        print "   Aborting! Error that caused failure:\n"
                        raise err
                    return err_val
            return caught
        return wrapper
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Creating liquid layouts is an immense pain. Now, I totally understand that tables should
Creating a google map with store locations within 50 miles of user entered address.
Error creating bean with name 'sessionFactory' defined in class path resource [ApplicationContext.xml]: Invocation of
I was wondering if it's frowned upon to use the decorator module that comes
I've been thinking about creating a Java framework that would allow programmers to specify
When creating decorators for use on class methods, I'm having trouble when the decorator
Hello all I am creating a horizontal menu for a site that needs to
I have been trying to create a decorator that can be used with both
Currently creating a windows form application program based on the decorator pattern in C#.
I am creating navigation menu. I want to use css so that anchor tag

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.