Manually raising (throwing) an exception in Python

前端 未结 8 1128
长发绾君心
长发绾君心 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))
    
    0 讨论(0)
  • 2020-11-22 04:28

    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')
    
    0 讨论(0)
提交回复
热议问题