异常,在程序运行时出现非正常情况时会被抛出,比如常见的名称错误、键错误等。

异常:

>>> s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>>

断言,判断某个表达式的真假,真则程序继续执行,否则抛出 AssertionError 异常。

断言:

>>> assert 3 < 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>>

  断言能够帮助别人或未来的你理解代码,找出程序中逻辑不对的地方。一方面,断言会提醒你某个对象应该处于何种状态,另一方面,如果某个时候断言为假,会抛出 AssertionError 异常,很有可能终止程序。

相关文章:

  • 2022-12-23
  • 2022-03-04
  • 2021-06-12
  • 2018-12-25
  • 2021-07-01
  • 2022-12-23
  • 2021-10-02
猜你喜欢
  • 2022-12-23
  • 2021-04-11
  • 2021-10-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案