# Cannot concatenate int and string types, will give error
def function_with_error():
number = 123
string = '123'
print(number + string)
# function will print 123123
def function_without_error():
string = '123'
string2 = '123'
print(string + string2)
def test_function(func):
print('--------------------------------------------------')
print('Testing function: ' + func)
# try tests function, if error occurs will run code in except
try:
eval(func)
except:
# print error occured if error occurs
print('error occured while testing ' + func)
else:
print('No errors occured in ' + func + '!')
print('Output is above.')
test_function('function_with_error()')
test_function('function_without_error()')
--------------------------------------------------
Testing function: function_with_error()
error occured while testing function_with_error()
--------------------------------------------------
Testing function: function_without_error()
123123
No errors occured in function_without_error()!
Output is above.
This is nice and all, being able to tell when an error occurs, but knowing that an error exists isn’t very useful, we would find that out either way from attempting to run it. A nice step would be the print the type of error that occurs. This is done as shown below.
# Cannot concatenate int and string types, will give error
def function_with_error():
number = 123
string = '123'
print(number + string)
# function will print 123123
def function_with_error2():
number = 12
number2 = 0
print (number / number2)
def test_function(func):
print('--------------------------------------------------')
print('Testing function: ' + func)
# try tests function, if error occurs will run code in except
try:
eval(func)
# store exception type in variable error
except Exception as error:
# print error occured if error occurs
print('The following error occured while testing ' + func + ': ')
print(error)
else:
print('No errors occured in ' + func + '!')
print('Output is above.')
test_function('function_with_error()')
test_function('function_with_error2()')
--------------------------------------------------
Testing function: function_with_error()
The following error occured while testing function_with_error():
unsupported operand type(s) for +: 'int' and 'str'
--------------------------------------------------
Testing function: function_with_error2()
The following error occured while testing function_with_error2():
division by zero