26  Python: Capture Error & Warning

26.1 Example 1

Code
import numpy as np

def fn_Mean(x, **kwargs):
    
    try:
        na_rm = kwargs.get('na_rm', False)
        if na_rm:
            x = x[~np.isnan(x)]
        xn = len(x)
        AM = np.sum(x) / xn
        GM = np.prod(x) ** (1 / xn)
        HM = xn / np.sum(1 / x)
        Mean = {'AM': AM, 'GM': GM, 'HM': HM}
        return Mean
    
    except Exception as e:
        print("\n An error has occurred! The error message is below. \n")
        print(e)
        
    except Warning as w:
        print("\n A warning has occurred! The warning message is below. \n")
        print(w)
        
    finally:
        print("\n Completed the fn_Mean run! \n")

26.2 Call 1: No error or warning

Code
A = np.array([np.nan, 12, 15, 14, 18])
fn_Mean(A, na_rm = True)

 Completed the fn_Mean run! 
{'AM': 14.75, 'GM': 14.593795674586724, 'HM': 14.441260744985673}

26.3 Call 2: Warning

Code
B = np.array([np.nan, -12, 15, 14, 18])
fn_Mean(B, na_rm = True)

 Completed the fn_Mean run! 
{'AM': 8.75, 'GM': nan, 'HM': 36.2589928057554}

RuntimeWarning: invalid value encountered in double_scalars

26.4 Call 3: No error or warning

Code
import math
C = np.array([np.nan, 12, math.inf, 14, 18])
fn_Mean(C, na_rm = True)

 Completed the fn_Mean run! 
{'AM': inf, 'GM': inf, 'HM': 19.0188679245283}

26.5 Call 4: Warning

Code
D = np.array([np.nan, 12, 0, 14, 18])
fn_Mean(D, na_rm = True)

 Completed the fn_Mean run! 
{'AM': 11.0, 'GM': 0.0, 'HM': 0.0}

RuntimeWarning: divide by zero encountered in divide

26.6 Call 5: No error or warning

Code
E = np.array([np.nan, 12, 0, np.nan, 18])
fn_Mean(E, na_rm = True)

 Completed the fn_Mean run! 
{'AM': 10.0, 'GM': 0.0, 'HM': 0.0}

26.7 Call 6: No error or warning

Code
G = np.array([np.nan, 12, 0, True, False])
fn_Mean(G, na_rm = True)

 Completed the fn_Mean run! 
{'AM': 3.25, 'GM': 0.0, 'HM': 0.0}

26.8 Call 7: Error

Code
H = np.array([np.nan, 12, 0, 'A', 18])
fn_Mean(H, na_rm = True)

 An error has occurred! The error message is below. 

ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

 Completed the fn_Mean run! 

26.9 Call 8: Error

Code
fn_Mean(J, na_rm = True)
NameError: name 'J' is not defined

26.10 Call 9: No warning or error

Code
G = np.array([np.nan, 12, 0, True, False])
fn_Mean(G, na_rm = True)

 Completed the fn_Mean run! 
{'AM': 3.25, 'GM': 0.0, 'HM': 0.0}

26.11 Call 10: No error or warning

Code
G = np.array([np.nan, 12, 0, True, False])
fn_Mean(G, na_rm = 'True')

 Completed the fn_Mean run! 
{'AM': 3.25, 'GM': 0.0, 'HM': 0.0}