Exception Handling in Functions¶
Let us go through the details about exception handling in functions
In [1]:
def sum_n(n):
try:
return int((n * (n + 1) / 2))
except ValueError:
print(f'{n} is not valid integer')
return
In [2]:
def sum_of_integers(lb, ub):
try:
return sum_n(ub) - sum_n(lb - 1)
except Exception:
print(f'Unable to get sum of integers between {lb} and {ub}')
In [3]:
sum_of_integers(3, 10)
Out[3]:
52
In [4]:
sum_of_integers(3, '10')
Unable to get sum of integers between 3 and 10
In [5]:
def sum_n(n):
try:
return int((n * (n + 1) / 2))
except ValueError:
print(f'{n} is not valid integer')
return
In [6]:
def sum_of_integers(lb, ub):
try:
if lb >= ub:
raise ValueError
return sum_n(ub) - sum_n(lb - 1)
except ValueError:
print(f'{lb} and {ub} are not valid to get sum of integers between them')
In [7]:
sum_of_integers(3, 10)
Out[7]:
52
In [8]:
sum_of_integers(3, 2)
3 and 2 are not valid to get sum of integers between them
In [9]:
def sum_n(n):
try:
return int((n * (n + 1) / 2))
except ValueError:
print(f'{n} is not valid integer')
return
In [10]:
def sum_of_integers(lb, ub):
try:
assert lb < ub, f'{ub} is not greater than {lb}'
return sum_n(ub) - sum_n(lb - 1)
except ValueError:
print(f'{lb} and {ub} are not valid to get sum of integers between them')
In [11]:
sum_of_integers(3, 10)
Out[11]:
52
In [12]:
sum_of_integers(3, 2)
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Input In [12], in <cell line: 1>() ----> 1 sum_of_integers(3, 2) Input In [10], in sum_of_integers(lb, ub) 1 def sum_of_integers(lb, ub): 2 try: ----> 3 assert lb < ub, f'{ub} is not greater than {lb}' 4 return sum_n(ub) - sum_n(lb - 1) 5 except ValueError: AssertionError: 2 is not greater than 3