How can I raise an exception in Python so that it can later be caught via an except
block?
Another way to throw an exceptions is assert. You can use assert to verify a condition is being fulfilled if not then it will raise AssertionError
. For more details have a look here.
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
You should learn the raise statement of python for that. It should be kept inside the try block. Example -
try:
raise TypeError #remove TypeError by any other error if you want
except TypeError:
print('TypeError raised')