<jupyter_start><jupyter_text>Scientific Computing with Python (Second Edition) Chapter 12This notebook file requires Jupyter notebook version >= 5 as it uses cell tagging to avoid that execution stops when intentionally exceptions are raises in a a cell.*We start by importing all from Numpy. As explained in Chapter 01 the examples are written assuming this import is initially done.*<jupyter_code>from numpy import *
def f(x):
    return 1/x

f(2.5)
f(0)
a = arange(8.0) 
a
a[3] = 'string'<jupyter_output><empty_output><jupyter_text>12.1.1 Basic principles<jupyter_code>raise Exception("Something went wrong")
print("The algorithm did not converge.")
raise Exception("The algorithm did not converge.")
def factorial(n):
    if not (isinstance(n, (int, int32, int64))):
       raise TypeError("An integer is expected")
    if not (n >=0): 
       raise ValueError("A positive number is expected")
    ...
print(factorial(5.2))
print(factorial(-5))
try: 
    f = open('data.txt', 'r') 
    data = f.readline() 
    value = float(data) 
except FileNotFoundError as FnF: 
    print(f' {FnF.strerror}: {FnF.filename}') 
except ValueError: 
    print("Could not convert data to float.")<jupyter_output>Could not convert data to float.<jupyter_text>12.1.2 User-defined exceptions<jupyter_code>class MyError(Exception):
    def __init__(self, expr):
        self.expr = expr
    def __str__(self):
        return str(self.expr)

try:
   x = random.rand()
   if x < 0.5:
      raise MyError(x)
except MyError as e:
   print("Random number too small", e.expr)
else:
   print(x)<jupyter_output>Random number too small 0.30562532079102633<jupyter_text>12.1.3 Context managers – the with statement<jupyter_code>with open('data.txt', 'w') as f:
    process_file_data(f)
f = open('data.txt', 'w')
try: 
    # some function that does something with the file 
    process_file_data(f) 
except:
    ...
finally:
    f.close()
import numpy as np      # note, sqrt in NumPy and SciPy 
                        # behave differently in that example
with errstate(invalid='ignore'):
    print(np.sqrt(-1)) # prints 'nan'

with errstate(invalid='warn'):
    print(np.sqrt(-1)) # prints 'nan' and 
                   # 'RuntimeWarning: invalid value encountered in sqrt'

with errstate(invalid='raise'):
    print(np.sqrt(-1)) # prints nothing and raises FloatingPointError<jupyter_output>nan
nan<jupyter_text>12.2 Finding errors: debugging 12.2.1 Bugsno code 12.2.2 The stack<jupyter_code>def f():
   g()
def g():
   h()
def h():
   1//0

f()
def f(a):
   g(a)
def g(a):
   h(a)
def h(a):
   raise Exception(f'An exception just to provoke a strack trace and a value a={a}')

f(23)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12058057312988463, 'fraction_numerical': 0.026051358392259024, 'mean_word_length': 3.7914438502673797, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '33374', 'license': 'MIT', 'n_tokens_mistral': 942, 'n_tokens_neox': 889, 'n_words': 280, 'path': 'Chapter12/chapter12.ipynb', 'repo_name': 'mazhengcn/scientific-computing-with-python', 'size': '2687'}