1、try except

公司主营业务:成都网站制作、做网站、外贸营销网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联推出大英免费做网站回馈大家。
忽略异常的最常见方法是使用语句块try except,然后在语句 except 中只有 pass。
import contextlib
class NonFatalError(Exception):
pass
def non_idempotent_operation():
raise NonFatalError(
'The operation failed because of existing state'
)
try:
print('trying non-idempotent operation')
non_idempotent_operation()
print('succeeded!')
except NonFatalError:
pass
print('done')
# output
# trying non-idempotent operation
# done在这种情况下,操作失败并忽略错误。
2、contextlib.suppress()
try:except 可以被替换为 contextlib.suppress(),更明确地抑制类异常在 with 块的任何地方发生。
import contextlib
class NonFatalError(Exception):
pass
def non_idempotent_operation():
raise NonFatalError(
'The operation failed because of existing state'
)
with contextlib.suppress(NonFatalError):
print('trying non-idempotent operation')
non_idempotent_operation()
print('succeeded!')
print('done')
# output
# trying non-idempotent operation
# done以上就是python忽略异常的两种方法,希望对大家有所帮助。更多Python学习指路:创新互联Python教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。