1.

Debugging in Python

Answer»

Raising Exceptions with raise statement:

The raise statement is used to raise exceptions and consists of 3 components:


  • raise keyword

  • Exception() function call

  • Parameter of the Exception() function, which usually contains an error message.

raise Exception("Error Occurred!!")
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 traceback
try:
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.
Writing an assert statement has the following components as a part of it,


  • assert keyword

  • a condition that results in a boolean value

  • a display message for when the assertion fails

  • a comma separating the condition and the display message.

>>> sum = 4
>>> 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


Discussion

No Comment Found