Skip to content

异常是在程序运行期间出现的错误,会干扰程序的正常执行流程。 Python 提供了异常处理机制,能让你捕获并处理这些异常,从而保证程序的健壮性和稳定性。

1. NameError

当你使用了一个未定义的变量、函数、类或模块名时,就会触发该异常。

python
print(val)
# NameError: name 'val' is not defined. Did you mean: 'eval'?

2. ValueError

当函数接收到一个正确类型但值不合适的参数时,就会抛出该异常。

python
num = int('ChatGIS')
# ValueError: invalid literal for int() with base 10: 'ChatGIS'

3. IndexError

当你尝试访问序列(如列表、元组、字符串)、字节对象、范围对象等数据结构里不存在的索引位置时,就会触发这个异常。

python
my_list = [1, 2, 3]
val1 = my_list[5]
# IndexError: list index out of range

4. KeyError

当你尝试访问字典中不存在的键时,就会引发 KeyError

python
dict1 = {
    'name': 'ChatGIS',
    'blog': 'https://chatgis.space/'
}
print(dict1['name'])
print(dict1['age'])
# KeyError: 'age'

5. AttributeError

当你尝试访问对象不存在的属性或方法时,就会触发该异常。

python
my_list = [1, 2, 3]
my_list.add(4)
# AttributeError: 'list' object has no attribute 'add'

6. TypeError

当操作或函数应用于不兼容类型的对象时会抛出该异常。

python
num = 10
string = "20"
result = num + string
# TypeError: unsupported operand type(s) for +: 'int' and 'str'