Python异常类型
Python 内置异常类型对应不同错误场景,理解异常类型有助于精准处理错误。
常见异常类型
ValueError(值错误)
Python
# 无效值转换
int("abc") # ValueError: invalid literal for int() with base 10: 'abc'
# 无效参数值
math.sqrt(-1) # ValueError: math domain error
# 处理示例
try:
age = int(input("输入年龄: "))
if age < 0:
raise ValueError("年龄不能为负")
except ValueError as e:
print(f"输入错误: {e}")
TypeError(类型错误)
Python
# 类型不匹配运算
"hello" + 10 # TypeError: can only concatenate str to str
# 无效类型调用
len(123) # TypeError: object of type 'int' has no len()
# 调用参数类型错误
int([1, 2]) # TypeError: int() argument must be a string...
# 处理示例
try:
result = "hello" + 10
except TypeError:
print("类型不匹配,无法运算")
IndexError(索引越界)
Python
# 列表索引越界
lst = [1, 2, 3]
lst[5] # IndexError: list index out of range
# 处理示例
try:
lst = [1, 2, 3]
print(lst[10])
except IndexError:
print("索引超出范围")
KeyError(键不存在)
Python
# 字典键不存在
d = {"a": 1}
d["b"] # KeyError: 'b'
# 处理示例
try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("键不存在")
# 推荐:使用 get 方法避免异常
d.get("b", "默认值") # 返回默认值,不抛异常
FileNotFoundError(文件不存在)
Python
# 打开不存在的文件
open("missing.txt", "r") # FileNotFoundError
# 处理示例
try:
with open("data.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("文件不存在")
ZeroDivisionError(除零错误)
Python
# 除数为零
10 / 0 # ZeroDivisionError: division by zero
# 处理示例
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
AttributeError(属性不存在)
Python
# 对象无该属性
"hello".append(1) # AttributeError: 'str' object has no attribute 'append'
# 处理示例
try:
s = "hello"
s.append("world")
except AttributeError:
print("字符串没有 append 方法")
异常层级
主要异常继承关系
text
Exception(所有普通异常的父类)
├── ArithmeticError(算术错误)
│ ├── ZeroDivisionError
│ ├── FloatingPointError
│ └── OverflowError
├── LookupError(查找错误)
│ ├── IndexError
│ └── KeyError
├── ValueError
├── TypeError
├── AttributeError
├── OSError(系统错误)
│ ├── FileNotFoundError
│ ├── PermissionError
│ └── IOError
├── RuntimeError
├── StopIteration
异常对比表
| 异常类型 | 触发场景 | 示例 |
|---|---|---|
| ValueError | 无效值 | int("abc") |
| TypeError | 类型错误 | "a" + 1 |
| IndexError | 索引越界 | lst[100] |
| KeyError | 键不存在 | d["x"] |
| ZeroDivisionError | 除零 | 1/0 |
| AttributeError | 属性不存在 | obj.xxx |
| FileNotFoundError | 文件不存在 | open("x") |
| PermissionError | 权限不足 | open("/root/x") |
自定义异常
创建自定义异常
Python
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
# 使用自定义异常
def validate_age(age):
if age < 0:
raise CustomError("年龄不能为负")
return age
try:
validate_age(-1)
except CustomError as e:
print(e.message)
异常处理策略
精准捕获
Python
try:
value = int(input())
result = lst[value]
except ValueError:
print("输入无效数字")
except IndexError:
print("索引超出范围")
使用父类捕获同类异常
Python
# 捕获所有查找错误
try:
lst[10]
d["key"]
except LookupError: # 捕获 IndexError 和 KeyError
print("查找错误")
要点总结
- ValueError:值无效或转换失败
- TypeError:类型不匹配或操作不支持
- IndexError:序列索引超出范围
- KeyError:字典键不存在
- 使用 get()、in 等方法可预防部分异常
📝 发现内容有误?点击此处直接编辑