Python中如何进行有效的异常捕获与处理?

2026-05-21 18:385阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计749个文字,预计阅读时间需要3分钟。

Python中如何进行有效的异常捕获与处理?

在Python代码中,尝试访问列表和字典的元素时可能会引发KeyError异常。以下是对给定代码的简化

python异常处理示例异常列表=['zouzou', 'jack', 'bob']字典={'001': 'hello'}try: print(异常列表[3]) print(字典['002'])except KeyError as 错误: print(索引或键不存在:, 错误)

异常

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:
print(lis[3])
print(name['002'])

except KeyError as e: # 将具体的错误信息赋值给e
print('没有这个key:', e)

except IndexError as e:
print('列表操作错误:', e)

结果

列表操作错误: list index out of range

出一个错就不往下执行了

也可以这样写

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:
print(lis[3])
print(name['002'])

except (KeyError, IndexError) as e:
print('没有这个key:', e)

抓住所有错误

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:
print(lis[3])
print(name['002'])
except Exception as e: # 基本上能抓住所有异常,缩进等 一些异常抓不了
print('出错了,错误为:', e)

结果

出错了,错误为: list index out of rangelis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:

open('test.txt')

except IndexError as e:
print('列表错误:', e)

except KeyError as e:
print('key错误:', e)

except Exception as e: # 上面的错误都不是时执行这里的
print('未知错误')

结果

未知错误

else在没有异常时执行

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:

print(lis[0])

except IndexError as e:
print('列表错误:', e)

except KeyError as e:
print('key错误:', e)

except Exception as e: # 上面的错误都不是时执行这里的
print('未知错误', e)

else:
print('一切正常') # 没有异常时执行

结果:

zouzou
一切正常lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:

print(lis[6])

except IndexError as e:
print('列表错误:', e)

except KeyError as e:
print('key错误:', e)

except Exception as e: # 上面的错误都不是时执行这里的
print('未知错误', e)

else:
print('一切正常') # 没有错误时执行

finally:
print('不管有没有错都执行') # 不管有没有错都执行,无论如何都会执行 操作系统资源归还的工作

结果

列表错误: list index out of range
不管有没有错都执行

自定义异常

class LfjException(Exception): # 继承异常的基类
def __init__(self, msg):
self.message = msg

def __str__(self):
return self.message


try:
raise LfjException('我的异常')

except LfjException as e:
print(e) # 打印的是self.message的值,self.message这 里的值是raise LfjException('我的异常'),括 号里的值

结果:

Python中如何进行有效的异常捕获与处理?

我的异常

raise主动抛异常

try:
num = int(input('>>>'))
except Exception:
print('在出现了异常之后做点儿什么,再让它抛异常')
raise # 原封不动的抛出try语句中出现的异常



本文共计749个文字,预计阅读时间需要3分钟。

Python中如何进行有效的异常捕获与处理?

在Python代码中,尝试访问列表和字典的元素时可能会引发KeyError异常。以下是对给定代码的简化

python异常处理示例异常列表=['zouzou', 'jack', 'bob']字典={'001': 'hello'}try: print(异常列表[3]) print(字典['002'])except KeyError as 错误: print(索引或键不存在:, 错误)

异常

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:
print(lis[3])
print(name['002'])

except KeyError as e: # 将具体的错误信息赋值给e
print('没有这个key:', e)

except IndexError as e:
print('列表操作错误:', e)

结果

列表操作错误: list index out of range

出一个错就不往下执行了

也可以这样写

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:
print(lis[3])
print(name['002'])

except (KeyError, IndexError) as e:
print('没有这个key:', e)

抓住所有错误

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:
print(lis[3])
print(name['002'])
except Exception as e: # 基本上能抓住所有异常,缩进等 一些异常抓不了
print('出错了,错误为:', e)

结果

出错了,错误为: list index out of rangelis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:

open('test.txt')

except IndexError as e:
print('列表错误:', e)

except KeyError as e:
print('key错误:', e)

except Exception as e: # 上面的错误都不是时执行这里的
print('未知错误')

结果

未知错误

else在没有异常时执行

lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:

print(lis[0])

except IndexError as e:
print('列表错误:', e)

except KeyError as e:
print('key错误:', e)

except Exception as e: # 上面的错误都不是时执行这里的
print('未知错误', e)

else:
print('一切正常') # 没有异常时执行

结果:

zouzou
一切正常lis = ['zouzou', 'jack', 'bob']
name = {'001': 'hello'}
try:

print(lis[6])

except IndexError as e:
print('列表错误:', e)

except KeyError as e:
print('key错误:', e)

except Exception as e: # 上面的错误都不是时执行这里的
print('未知错误', e)

else:
print('一切正常') # 没有错误时执行

finally:
print('不管有没有错都执行') # 不管有没有错都执行,无论如何都会执行 操作系统资源归还的工作

结果

列表错误: list index out of range
不管有没有错都执行

自定义异常

class LfjException(Exception): # 继承异常的基类
def __init__(self, msg):
self.message = msg

def __str__(self):
return self.message


try:
raise LfjException('我的异常')

except LfjException as e:
print(e) # 打印的是self.message的值,self.message这 里的值是raise LfjException('我的异常'),括 号里的值

结果:

Python中如何进行有效的异常捕获与处理?

我的异常

raise主动抛异常

try:
num = int(input('>>>'))
except Exception:
print('在出现了异常之后做点儿什么,再让它抛异常')
raise # 原封不动的抛出try语句中出现的异常