InterviewSolution
| 1. |
Debugging in Python |
|
Answer» Raising Exceptions with raise statement: The raise statement is used to raise exceptions and consists of 3 components:
Traceback (most recent call last): File "./prog.py", line 1, in <module> Exception: Error Occurred!! Traceback as String There is a function in python called traceback.format_exc() which returns the traceback displayed by Python when a raised Exception is not handled as a String type. The Traceback Module is required to be imported for this purpose. Example: import tracebacktry: raise Exception('Error Message.') except: with open('error.txt', 'w') as error_file: error_file.write(traceback.format_exc()) print('The traceback info was written to error.txt.') Output: The traceback info was written to error.txt. Assert Statements in Python: Assert Statements/Assertions are widely used for debugging programs and checking if the code is performing some operation that is obviously wrong according to the logic of the program. The special thing about assert is that when an assert fails, the program immediately crashes, allowing us to narrow down our search space for the bug.
>>> assert sum == 5, 'Addition Error' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: Addition Error Assertions can be disabled by passing the -O option when running Python as shown in the commands below. $ python -Oc "assert False"$ python -c "assert False" Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError |
|