I logically want to connect a user defined exception with general exception handling. Firstly, it should be checked whether the user defined exception is triggered. If it is not triggered, but another exception occurs, I want to print the exception information by get_exception_info().
I have the following code:
class TestException(Exception):
pass
def get_exception_info():
try:
exception_type, exception_value, exception_traceback = sys.exc_info()
file_name, line_number, procedure_name, line_code = traceback.extract_tb(exception_traceback)[-1] #this line is properly indented in my file
exception_info = ''.join('[Time Stamp]: '
+ str(time.strftime('%d-%m-%Y %I:%M:%S %p'))
+ '' + '[File Name]: ' + str(file_name) + ' '
+ '[Procedure Name]: ' + str(procedure_name) + ' '
+ '[Error Message]: ' + str(exception_value) + ' '
+ '[Error Type]: ' + str(exception_type) + ' '
+ '[Line Number]: ' + str(line_number) + ' '
+ '[Line Code]: ' + str(line_code))
return exception_info
except:
pass
def test_func(x):
try:
if x > 0:
raise TestException('wrong')
elif x < 0:
raise TestException('right')
else:
pass
except TestException as e:
print(e)
except Exception:
exception_info = get_exception_info()
print(exception_info)
finally:
pass
test_func(a)
Theoretically, this would cause an Exception and it should print out the result of get_exception_info(). However I just get "NameError: name 'a' is not defined.
What am I doing wrong? And, more importantly probably, is this the right way to archieve my goal?
Thank you!