Manually raising (throwing) an exception in Python

前端 未结 8 1185
长发绾君心
长发绾君心 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:17

    For the common case where you need to throw an exception in response to some unexpected conditions, and that you never intend to catch, but simply to fail fast to enable you to debug from there if it ever happens — the most logical one seems to be AssertionError:

    if 0 < distance <= RADIUS:
        #Do something.
    elif RADIUS < distance:
        #Do something.
    else:
        raise AssertionError("Unexpected value of 'distance'!", distance)
    

提交回复
热议问题