Python 的 抑制异常

等级 4151 次按键

这使用suppress()静默忽略特定异常。

Python 代码

# suppress是忽略指定异常的上下文管理器
1from contextlib import suppress
# os提供remove等文件操作
2import os
3
# 相当于一行写成的try/except FileNotFoundError: pass
4with suppress(FileNotFoundError):
# 文件不存在,因此抛出FileNotFoundError
5 os.remove("nonexistent_file.txt")
# 不会执行:异常发生后块中剩余部分被跳过
6 print("Removed")
7
# 异常已被吞掉,所以程序从这里继续执行
8print("Continuing...")

运行结果

Continuing...
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • "× 6
  • .× 5
  • (× 4
  • )× 4
  • _× 1
  • :× 1

Python 等级 4 的更多代码示例

← 返回 Python 打字练习