## 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)
```