Reputation: 133
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'
Upvotes: 0
Views: 480
Reputation: 1790
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...)
Upvotes: 1