Manually raising (throwing) an exception in Python

前端 未结 8 1194
长发绾君心
长发绾君心 2020-11-22 03:38

How can I raise an exception in Python so that it can later be caught via an except block?

8条回答
  •  野的像风
    2020-11-22 04:27

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

提交回复
热议问题