0

Im trying to build a definition that does error checking for my definitions. What is the proper way to structure this code for error handling?

I want the script to run a specified definition, if it fails, retry a number of times, then kill it if it times out.

import time

def open_file():
    open('testfile.py')

def run_def(definition):
    for i in range(0, 4):
        try:
            definition
            str_error = None
        except Exception as str_error:
            pass
            if str_error:
                time.sleep(1)
                print(str_error)
            else:
                break
                print('kill script')

run_def(open_file())

I get an error when I try passing the definition into the error check definition. But the script works if I dont put the error checker into a separate definition.

FileNotFoundError: [Errno 2] No such file or directory: 'testfile.py'
5
  • I'm not sure what you're trying to do here. Your open_file function returns None. So doing run_def(open_file()) calls run_def with an arg of None. And so definition in the try block won't ever raise an exception. Commented May 16, 2018 at 15:05
  • Are you perchance running run_def and open_file in different folders? Try using an absolute path to the file. Also, for what you are doing - try looking at decorators realpython.com/primer-on-python-decorators Commented May 16, 2018 at 15:15
  • Im not really opening a file, Im just trying to create a generic error Commented May 16, 2018 at 15:18
  • Try to remove call on parameter run_def(open_file) then in function do definition(). Normally error will be catched. Commented May 16, 2018 at 15:25
  • It is unclear what you are trying to do, but I would think run_def should just check the condition of definition and return, you can have a loop that calls it x number of times. Commented May 16, 2018 at 15:25

1 Answer 1

1

I'm not sure to understand what you're trying to do, but if you want to catch exception, your call function should be placed in your try / except block.

Like this:

import time

def open_file():
    open('testfile.py')

def run_def(definition):
    for i in range(0, 4):
        try:
            definition()
        except Exception as str_error:
            if str_error:
                time.sleep(1)
                print(str_error)
            else:
                break
                print('kill script')

run_def(open_file)

You don't need to pass after except.

And you don't need to initialize str_error variable before. (Unless you use it before...)

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.