十种常见Python异常与案例分析
在Python编程中,我们可能会遇到各种异常。以下是我总结的十种常见Python异常及其案例分析:
ZeroDivisionError
:除数为0。
案例:try:
div_num = 1 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
ValueError
:提供的值不在有效范围内。
案例:try:
age = int(input("Enter your age: ")) < 0
except ValueError as e:
print(f"Error: {e}")
TypeError
:数据类型不匹配。
案例:try:
str_num = "123"
int_num = int(str_num)
except TypeError as e:
print(f"Error: {e}")
FileNotFoundError
:指定的文件不存在。
案例:try:
with open("non_existent_file.txt", "r") as f:
content = f.read()
except FileNotFoundError as e:
print(f"Error: {e}")
KeyError
:字典中找不到指定的键。
案例:try:
my_dict = {"name": "John", "age": 30}
value = my_dict["country"] # KeyError: 'country'
except KeyError as e:
print(f"Error: {e}")
IndexError
:列表、元组或其他序列的索引超出范围。
案例:try:
my_list = [1, 2, 3]
value = my_list[4] # IndexError: list index out of range
except IndexError as e:
print(f"Error: {e}")
TypeError
:在不同数据类型间进行操作可能会引发错误。
案例:try:
str_num = "123"
int_num = int(str_num) + 5 # TypeError: can only concatenate str (not "int") to str
print(int_num))
except TypeError as e:
print(f"Error: {e}")
AttributeError
:在对象上查找不存在的属性时,会引发这个错误。
案例:class Person:
def __init__(self, name):
self.name = name
try:
obj = Person("Alice")
print(obj.age) # AttributeError: 'Person' object has no attribute 'age'
except AttributeError as e:
print(f"Error: {e}")
RecursionError
:当递归调用超过Python语言规定的限制时,会引发这个错误。
案例:def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1))
try:
result = factorial(5)
print(result)
except RecursionError as e:
print(f"Error: {e}")
SystemError
:在Python解释器遇到无法解析的代码时,会引发这个错误。虽然它不是标准异常类型,但在某些情况下,它可能会被抛出。
以上就是Python中十种常见异常及其案例分析,希望对你理解和处理这些异常有所帮助。
还没有评论,来说两句吧...