Warning Exception In Python

Hi there, In this article, we will explore how to use warnings filter and warning categories in python. Also how we can use different warnings for different scenarios.

Warning messages are issued in situations where we warn the developer of situations that are not necessarily exceptions and it does not terminate the program. For example,  We might issue a warning when a program uses an obsolete module or certain programming elements such as some keywords,

functions, classes, etc. A warning in the program is distinct from an error. In simple words, the program gets terminated if an error occurred. but in case of a warning, it displays a warning message but the program runs.

Warning Categories.

Warning categories are useful to filter out groups of warnings. Also, developers can define additional warnings by subclassing one of the warning categories

Note: A warning category must be always a subclass of the warning class.

1. exception Warning

This is a base class of all warning category classes. And it is a subclass of Exception.

# program to illustrate warn()
# importing modules
import warnings
# displaying warning
warnings.warn('Warning Message')


Output: 
main.py:2: UserWarning: Geeks 4 Geeks
  warnings.warn('Geeks 4 Geeks')

2. exception UserWarning 

Base class for warning generated by code.

# program to illustrate warn()
# importing modules
import warnings
# displaying warning
x = 3
if x<4 :
       warnings.warn('Please Enter valid Number')

Output:
   
main.py:7: UserWarning: Please Enter valid Number
  warnings.warn('Please Enter valid Number')

Similarly, We can use warn methods listed below.

3. exception DeprecationWarning 

It is a base class for alerts regarding obsolete features when those warnings are intended for other python developers

By default, it’s ignored, but it can be triggered by code in the main.

4. exception PendingDeprecationWarning

This exception is also ignored by default. It is a base class for warning about features that are obsolete and can be deprecated in  future but not at the moment.

5. exception SyntaxWarning

It is a base class of warnings about dubious syntactic features.

6. exception RuntimeWarning

Base class of warnings for dubious behavior at run time or suspicious run time attributes.

#runtime warning 
#dividing 1 by zero cause runtime error
import warnings
try:
    print(1/0)
except :
   warnings.warn("caught an runtimeWarning", RuntimeWarning)

Output:  
main.py:8: RuntimeWarning: caught an runtimeWarning
  warnings.warn("caught an runtimeWarning", RuntimeWarning)

7. exception FutureWarning

It is a base class of warnings on obsolete features when certain warnings are meant for end-user of python written programs.

8. exception ImportWarning

Base class of warnings when there is a probable mistake in importing modules. By default, it is ignored by the filter. We can enable it with the python developer mode.

9. exception UnicodeWarning

Used to Display warnings that are related to the Unicode

10. exception EncodingWarning

Base class of warning related to encoding. Introduced in 3.10

11. exception BytesWarning

It is used to display a warning that is related to the bytes or byteArray.

12. exception ResourceWarning.

Base class for warnings related to resource usage. Also, it is ignored by default and can be used with python developer mode.

The Warning Filter:

It is used to handle warnings in python. The warning filter maintains an ordered list of filter specifications. and warning is matched against each filter specification till the warning gets matched. And Each entry is a tuple of the form (action, message, category, module, line no)

action values (string): 

1. default: display the first matching warning for each position.

2. error: Converts warning to raise an exception.

3. ignore: Never display warnings that match.

4. always: Always print matching warnings

5. module: First occurrence of warning for each module where warning issued. regardless of line no

6. once: Display the first matching warning regardless of location.

Message (string) :

The message is the string that contains a regular expression that must match the beginning of the warning.

Category: 

The category is the class of which the warning category must be a subclass in order to match.

Module:

The module is a string with a regular expression that must match the module name.

lineno:

An integer to match the number of line in which the warning appeared. or 0 to match any number of line.

Warning Functions:

Here is a list of some commonly used warning functions.

warn(message, category=none, stacklevel=1, source=none)

#function warn()
import warnings

# displaying warning
warnings.warn('The Code Hubs')


Output:
main.py:4: UserWarning: The Code Hubs
  warnings.warn('The Code Hubs')

filterwarnings(action, message=”, category=Warning, module=”, lineno=0, append=False) 

This function adds entry into the specifications of warning filter.

Program:

#program for filterwarnings
import warnings

# adding entry into the specifications
# of the warnings filter.
warnings.filterwarnings('ignore', '.*do not.*', )

# displaying warinings
warnings.warn('The Code Hubs  !')

# this warning will not be displayed
warnings.warn('Do not show this message')

Output: 
main.py:12: UserWarning: The Code Hubs  !
  warnings.warn('The Code Hubs  !')

simplefilter(action, category=Warning, lineno=0, append=False):

Used to add a single entry to the filter requirements list.

# simplefilter()
import warnings
warnings.simplefilter('error', UserWarning)
# display warning
warnings.warn('Hope You Find It Useful')


Output: 
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    warnings.warn('This is a warning message')
UserWarning: This is a warning message

With that, it covers almost every concept of warning for more give a visit to  The Warning Section of official documentation.

Thanks for the read.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories