NipGeihou's blog NipGeihou's blog
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档

NipGeihou

我见青山多妩媚,料青山见我应如是
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档
  • 教程

    • 安装
    • 流程控制与定义函数
    • 数据结构(类型)
    • 模块
    • 输入与输出
    • 错误与异常
      • 异常
      • 异常处理(try)
      • 异常抛出(raise)
      • 异常自定义
      • finally
      • with
    • 类
    • 标准库
    • 虚拟环境和包
    • 开发环境
    • ORM - SQLAlchemy
  • Python
  • 教程
NipGeihou
2024-10-11
目录

错误与异常

# 异常

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    10 * (1/0)
          ~^~
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    4 + spam*3
        ^^^^
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    '2' + 2
    ~~~~^~~
TypeError: can only concatenate str (not "int") to str

# 异常处理(try)

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")

异常实例对象:

except Exception as e:
    print(f'caught {type(e)}: e')

类似于 Java 的 catch(Exception e)

# 异常抛出(raise)

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise NameError('HiThere')
NameError: HiThere
  • 类似于 Java 的 throw new NameError("HiThere")
  • raise (opens new window) 唯一的参数就是要触发的异常。这个参数必须是异常实例或异常类(派生自 BaseException (opens new window) 类,例如 Exception (opens new window) 或其子类)
raise ValueError  # 'raise ValueError()' 的简化

如果只想判断是否触发了异常,但并不打算处理该异常,则可以使用更简单的 raise (opens new window) 语句重新触发异常:

>>> 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 <module>
    raise NameError('HiThere')
NameError: HiThere

# 异常自定义

直接或间接继承 Exception 类的类,即为异常类,约定异常类命名以 Error 结尾。具体如何定义类参考下章。

# finally

与其他语言的 try 语句类似,python 的 try 也有 finally 可选子句,作用也相似:任何情况下都会执行

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')

复杂示例

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("division by zero!")
    else: # try代码块正常执行(无异常)时触发
        print("result is", result)
    finally:
        print("executing finally clause")
        
divide(2, 1)


divide(2, 0)


divide("2", "1")

# with

自动处理释放资源逻辑

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")
上次更新: 2024/10/11, 23:55:46
输入与输出
类

← 输入与输出 类→

最近更新
01
iSCSI服务搭建
05-10
02
磁盘管理与文件系统
05-02
03
网络测试 - iperf3
05-02
更多文章>
Theme by Vdoing | Copyright © 2018-2025 NipGeihou | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式