Python --异常处理

目录

1, 异常处理

1-1, 单个except的try语句

1-2, 多个except的try语句

1-3, 多个异常写在一行

1-4, 捕获所有异常

1-5, else字句

1-6, finally字句

1-6, try-finally字句

2, 抛出异常

3, 断言

4, 异常和sys模块


1, 异常处理

1-1, 单个except的try语句

try:
    代码1 
except Exception as reason: 
    代码2 

Exception为异常处理器,用于捕获对应的异常,它是一个

reason异常处理参数,用于保存错误的原因, 该参数是可选,建议给出, 它是类的实例

说明:

若try中的代码块没有异常,则except语句不执行

try中的代码块有异常忽略异常开始行以后的代码跳转到except语句执行

若实际异常与except的异常处理器匹配执行except语句,进行异常处理

若实际异常与except的异常处理器不匹配异常会一直向上抛,直到找到对应的异常处理器,最终都没有找到的话,则会显示出跟踪记录后程序退出

# 异常处理器捕获到对应的异常
In [65]: try:
    ...:     float('aaa')
    ...: except ValueError as e:
    ...:     print('e:', e)
e: could not convert string to float: 'aaa'

# 异常处理器没有捕获到对应的异常,最后给出跟踪记录
# 实际的异常的ValueError, 异常处理器使用的是TypeError,所以没有捕捉到异常                             
In [66]: try:
    ...:     float('aaa')
    ...: except TypeError as e:
    ...:     print('e:', e)
    ...:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[66], line 2
      1 try:
----> 2     float('aaa')
      3 except TypeError as e:
      4     print('e:', e)

ValueError: could not convert string to float: 'aaa'

1-2, 多个except的try语句

当发生异常时,解释器在所有的except语句中匹配异常处理器,若找到对应的异常处理器,则跳进相应的except语句中进行异常处理

try:
    代码1 
except Exception1 as reason1:
    代码2 
except Exception2 as reason2:
...
except Exceptionn as reasonn:

    代码n

# 这里匹配到异常处理器ValueError, 则执行其下的代码
In [69]: try:
    ...:     float('aaa')
    ...: except TypeError as e:
    ...:     print('e1:', e)
    ...: except ValueError as e:
    ...:     print('e2:', e)
    ...: except NameError as e:
    ...:     print('e3:',e)
e2: could not convert string to float: 'aaa'

# 没有匹配到响应的异常处理器,显示出跟踪记录
In [70]: try:
    ...:     float('aaa')
    ...: except TypeError as e:
    ...:     print('e1:', e)
    ...: except IOError as e:
    ...:     print('e2:', e)
    ...: except NameError as e:
    ...:     print('e3:',e)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[70], line 2
      1 try:
----> 2     float('aaa')
      3 except TypeError as e:
      4     print('e:', e)

ValueError: could not convert string to float: 'aaa'

1-3, 多个异常写在一行

多个异常处理器可以写在一个except语句

try:
    代码1 
except (Exception1, Exception2,...,  Exceptionn) as reason1:
    代码2 

# 匹配到对应的异常处理器
In [71]: try:
    ...:     float('aaa')
    ...: except (ValueError, NameError, TypeError) as e:
    ...:     print('e:', e)
    ...:
e: could not convert string to float: 'aaa'

# 没有匹配到对应的异常处理器,显示跟踪记录,退出程序
In [72]: try:
    ...:     float('aaa')
    ...: except (IOError, NameError, TypeError) as e:
    ...:     print('e:', e)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[72], line 2
      1 try:
----> 2     float('aaa')
      3 except (IOError, NameError, TypeError) as e:
      4     print('e:', e)

ValueError: could not convert string to float: 'aaa'

1-4, 捕获所有异常

Exception所有异常类的父类,可用于捕获所有异常(除KeyboardInterrupt、SystemError以外), BaseException所有异常类的父类

# 通过Exception捕获异常
In [73]: try:
    ...:     float('aaa')
    ...: except Exception as e:
    ...:     print('e:', e)
    ...:
e: could not convert string to float: 'aaa'

# 通过BaseException捕获异常
In [74]: try:
    ...:     float('aaa')
    ...: except BaseException as e:
    ...:     print('e:', e)
    ...:
e: could not convert string to float: 'aaa'

1-5, else字句

else字句在try中的代码没有异常时才会执行, else语句需要放在except 字句后面

try:
    代码1 
except Exception as reason1:
    代码2 
else:
    代码3

# try中的代码没有异常, 执行else字句
In [77]: try:
    ...:     float('111')
    ...: except Exception as e:
    ...:     print('e:', e)
    ...: else:
    ...:     print('try中的代码没有异常')
    ...:
try中的代码没有异常

# try中的代码有异常, 不执行else字句
In [78]: try:
    ...:     float('aaa')
    ...: except Exception as e:
    ...:     print('e:', e)
    ...: else:
    ...:     print('try中的代码没有异常')
    ...:
e: could not convert string to float: 'aaa'

1-6, finally字句

finally字句无论异常是否发生,都会执行, finally字句放在最后

try:
    代码1 
except Exception as reason1:
    代码2 
else:
    代码3
finally:
    代码4

# try中无异常时,finally字句执行
In [79]: try:
    ...:     float('111')
    ...: except Exception as e:
    ...:     print('e:', e)
    ...: else:
    ...:     print('try中没有异常')
    ...: finally:
    ...:     print('finally无论是否有异常都会执行')
try中没有异常
finally无论是否有异常都会执行

# try中有异常时,finally字句执行
In [81]: try:
    ...:     float('111a')
    ...: except Exception as e:
    ...:     print('e:', e)
    ...: else:
    ...:     print('try中没有异常')
    ...: finally:
    ...:     print('finally无论是否有异常都会执行')
    ...:
e: could not convert string to float: '111a'
finally无论是否有异常都会执行

1-6, try-finally字句

try-finally字句不是用来捕获异常的,它常用来维持一致的行为, 如文件打开后需要关闭

try中有异常时,执行完finally语句后向上抛出异常

当finally中有异常时,finally的异常会覆盖try的异常向上抛出

try:
    代码1 
finally:
    代码2

In [84]: try:
    ...:     f = open(path)
    ...:     txtn = f.readlines()
    ...: finally:
    ...:     f.close()

2, 抛出异常

通过raise SomeException('message'),可抛出异常

In [1]: x = 1
In [3]: if x != 2:
   ...:     raise Exception('error')
   ...:
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[3], line 2
      1 if x != 2:
----> 2     raise Exception('error')

Exception: error

3, 断言

通过assert expression, messages, 来进行断言, expression为真, 则不报错,expression为假, 则输出messages信息

# 表达式为真时,不输出后面的报错信息
In [7]: assert 1 == 1 , 'is not ok'

# 表达式为假时,输出后面的报错信息, 退出程序
In [8]: assert 1 == 2 , 'is not ok'
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[8], line 1
----> 1 assert 1 == 2 , 'is not ok'

AssertionError: is not ok

# 通过try语句捕获断言异常
In [9]: try:
   ...:     assert 1 == 0, 'error'
   ...: except Exception as e:
   ...:     print('e:', e)
   ...:
e: error

4, 异常和sys模块

可以通过sys模块中的exc_info()获取异常信息

# sys.exc_info()获取异常信息,返回一个三元数元组
In [16]: try:
    ...:     float('aaa')
    ...: except:
    ...:     exc_tuple = sys.exc_info()

In [17]: print('exc_tuple:', exc_tuple)
exc_tuple: (<class 'ValueError'>, ValueError("could not convert string to float: 'aaa'"), <traceback object at 0x0000024948149D00>)

In [18]:

In [18]: for e in exc_tuple:
    ...:     print(e)
    ...:
<class 'ValueError'>
could not convert string to float: 'aaa'
<traceback object at 0x0000024948149D00>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值