Custom Exceptions in Conditions in Python
Special conditions are usually specified for throwing an exception.
Let's say we have a list:
lst = [1, 2, 3]
Let's set a condition: if the length of the list is less than or equal to three, then let the sum of the elements be calculated. Otherwise, in the else
block, let our ToBigLength
exception be thrown:
try:
if len(lst) <= 3:
print(sum(lst))
else:
raise ToBigLength
except ToBigLength:
print('error: list is too big')
After executing the code, the following will be displayed:
6
Now let's increase the number of items in the list:
lst = [1, 2, 3, 4]
try:
if len(lst) <= 3:
print(sum(lst))
else:
raise ToBigLength
except ToBigLength:
print('error: list is too big')
After executing the code, the following will be displayed:
'error: list is too big'
Write a condition: if the number is positive, then let it be squared. If the number is negative, then let the exception you created for the previous lesson be thrown.
Write a condition that if the number is not zero, then 5
is added to it. Otherwise, let the exception you created for the previous lesson be thrown.