版权声明:本文为博主原创文章,欢迎讨论共同进步。 https://blog.csdn.net/tz_zs/article/details/81479043
____tz_zs
assert 断言
https://docs.python.org/3/reference/simple_stmts.html#assert
Python assert 断言是声明其表达式为 True 的判定,如果为 False 则将抛出异常 AssertionError 。
简单:
assert 表达式
if not expression: raise AssertionError
复杂:
assert 表达式 [,错误信息]
if not expression1: raise AssertionError(error message)
示例代码:
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
"""
@author: tz_zs
"""
assert 1 == 2, "assert test"
"""
Traceback (most recent call last):
File "/home/zmate/tzzs/mytz/test_assert.py", line 11, in <module>
assert 1 == 2,"assert test"
AssertionError: assert test
"""
自定义异常
示例代码:
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
class MyExcept(Exception):
def __init__(self, message):
Exception.__init__(self)
self.message = message
def __str__(self):
return "自定义异常信息:%s" % self.message
if __name__ == '__main__':
try:
raise MyExcept("my异常")
except MyExcept, e:
print e
.
end