raise [Exception [, args [, traceback]]]
# 如果 x 大于 5 就触发异常
x = 10
if x > 5:
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
>>> try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
if not expression:
raise AssertionError
assert expression [, arguments]
if not expression:
raise AssertionError(arguments)
>>> assert True # 条件为 true 正常执行
>>> assert False # 条件为 false 触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1 # 条件为 true 正常执行
>>> assert 1==2 # 条件为 false 触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==2, '1 不等于 2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 不等于 2
import sys
assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
# 判断当前系统是否为 Linux,如果不满足条件则直接触发异常,不必执行接下来的代码
# 接下来要执行的代码