⊗pyPmExcFu 81 of 128 menu

Function with exception in Python

It is very convenient to throw exceptions by writing them in a function using conditions.

Let's make a function get_sum that will print the sum of the elements of a list only if the length of the list is less than or equal to 3. Otherwise, let our exception ToBigLength be thrown:

def get_sum(lst): if len(lst) <= 3: return sum(lst) else: raise ToBigLength

Now we pass the list to the get_sum function and output the function to the console:

lst = [1, 2, 3, 4] print(get_sum(lst)) # 6

You can also set up functions to catch multiple exception types. Let's create another exception class ToSmallLength:

class ToSmallLength(Exception): pass

Now let's write a condition in the function: if the length of the list is zero, then let ToSmallLength be thrown. If no exception is caught, then let the sum of all the elements of the list be output:

def get_sum(lst): if len(lst) > 3: raise ToBigLength if len(lst) == 0: raise ToSmallLength else: return sum(lst)

For convenience, we can enclose the list that will be passed to the function parameter, the function itself, and its call in the try block. And we will place the interception of our two exceptions in the except blocks:

try: lst = [1, 2, 3] res = get_sum(lst) print(res) except ToBigLength: print('error 1') except ToSmallLength: print('error 2')

Create a function that will take a number as a parameter. In it, write the conditions: if the number is negative and equal to zero, then let the corresponding exceptions be thrown. Otherwise, let the number be multiplied by 3.

Test the function you created using the try-except construct. Also catch your exceptions.

enru