InterviewSolution
| 1. |
How are warnings generated in Python? |
||||||||||||||||||||||
|
Answer» Exceptions are generally fatal as the program TERMINATES instantly when an unhandled exception occurs. Warnings are non-fatal. A warning message is displayed but the program won’t terminate. Warnings generally appear if some deprecated usage of CERTAIN programming element like keyword/function/class etc. occurs. Python’s builtins module defines Warnings class which is inherited from Exception itself. However, custom warning messages can be displayed with the help of WARN() function defined in built-in warnings module. There are a number of built-in Warning subclasses. User defined subclass can also be defined.
Following code defines WarnExample class. When method1() is called, it issues a depreciation warning. # warningexample.py import warnings class WarnExample: def __init__(self): self.text = "Warning" def method1(self): warnings.warn( "method1 is deprecated, USE new_method INSTEAD", DeprecationWarning if __name__=='__main__': e=WarnExample() e.method1()Output: $ python -Wd warningexample.py warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning |
|||||||||||||||||||||||