捕获异常

python完整的异常处理语法结构如下:

特别说明:

1.try块是必需的,except块和finally,当try块没有出现异常时,程序会执行else块

2.try块后只有一个except快块会被执行,不可能有多个except块被执行。

3.原则:先捕获小异常再捕获大异常

实例:

import sys

try:
a = int(sys.argv[1])
b = int(sys.argv[2])
c = a / b
print("您输入的两个数相除的结果是:",c)
except IndexError:
print("索引错误:运行程序时输入的参数个数不够")
except ValueError:
print("数值错误:程序只能接受整数参数")
except ArithmeticError:
print("算术错误")
except Exception:
print("未知异常") # 输出结果:
E:\myproj\crazy_python\07\7.2>python div_test.py 3 0
算术错误

单异常捕获

import sys

try:
a = int(sys.argv[1])
b = int(sys.argv[2])
c = a / b
print("您输入的两个数相除的结果是:",c)
except (IndexError, ValueError, ArithmeticError):
print("程序发生了数组越界、数字格式异常、算术异常之一")
except:
print("未知异常") # 输出结果
E:\myproj\crazy_python\07\7.2>python multi_exception_test.py 4 0
程序发生了数组越界、数字格式异常、算术异常之一

多异常捕获

def foo():
try:
fis = open("a.txt")
except Exception as e:
print(e)
print(e.args)
print(e.errno)
print(e.strerror) foo() # 输出结果:
[Errno 2] No such file or directory: 'a.txt'
(2, 'No such file or directory')
2
No such file or directory

访问异常信息

4. 1try或except中的return语句,不会影响finally块的执行;但是os._exit()语句会退出python解释器,导致finally块试去执行机会。

import os

def test():
fis = None
try:
fis = open("a.txt")
except OSError as e:
print(e.strerror)
return
os._exit(1)
finally:
if fis is not None:
try:
fis.close()
except OSError as ioe:
print(ioe.strerror)
print("执行finally里的资源回收!") test() # 输出结果:
No such file or directory
执行finally里的资源回收!

finally_1

4.1不能在finally块使用return或raise。finally块中的return或raise语句,会导致try、except块中的return、raise语句失效

def test():
try:
return True # 由于finally中包含return,该return语句失效
finally:
return False a = test()
print(a) # 输出结果
False

finally_2

抛出异常(使用raise引发异常)

不管是系统引发的异常,还是程序员使用raise手动引发的异常,python解释器对异常的处理没有任何差别,都可以使用try...except来捕获它

raise语句有如下三种常用用法:

def main():
try:
mtd(3)
except Exception as e:
print("程序出现异常:", e)
mtd(3) def mtd(a):
if a > 0:
raise ValueError("a的值大于0.不符合要求") main() # 输出结果:
D:\soft\python36\python.exe D:/myproject/crazy_python/07/7.3/raise_test.py
Traceback (most recent call last):
程序出现异常: a的值大于0.不符合要求
File "D:/myproject/crazy_python/07/7.3/raise_test.py", line 17, in <module>
main()
File "D:/myproject/crazy_python/07/7.3/raise_test.py", line 9, in main
mtd(3)
File "D:/myproject/crazy_python/07/7.3/raise_test.py", line 14, in mtd
raise ValueError("a的值大于0.不符合要求")
ValueError: a的值大于0.不符合要求

raise_1

except和raise同时使用

class AuctionException(Exception): pass
class AuctionTest:
def __init__(self, init_price):
self.init_price = init_price
def bid(self, bid_price):
d = 0.0
try:
d = float(bid_price)
except Exception as e:
# 此处只是简单地打印异常信息
print("转换出异常:", e)
# 再次引发自定义异常
# raise AuctionException("竞拍价必须是数值,不能包含其他字符!") # ①
raise AuctionException(e)
if self.init_price > d:
raise AuctionException("竞拍价比起拍价低,不允许竞拍!")
initPrice = d
def main():
at = AuctionTest(20.4)
try:
at.bid("df")
except AuctionException as ae:
# 再次捕获到bid()方法中的异常,并对该异常进行处理
print('main函数捕捉的异常:', ae)
main() # 输出结果:
转换出异常: could not convert string to float: 'df'
main函数捕捉的异常: could not convert string to float: 'df'

except_raise

最新文章

  1. 前端自学路线之js篇
  2. ABP源码分析十一:Timing
  3. ImageLoader图片加载
  4. HDU 5762
  5. user-select : 保护版权内容的简单方案
  6. Linux 发送信号
  7. Java开发环境准备
  8. Qt 打开指定的文件
  9. 如何利用Jmeter做代理录制脚本
  10. SDL2源代码分析4:纹理(SDL_Texture)
  11. 04 前端篇(JQuery)
  12. .Net程序员学用Oracle系列(19):导出、导入(备份、还原)
  13. JS获取元素的宽高以及offsetTop,offsetLeft等的属性值
  14. GD32 ------ 使用外部中断,中断函数需要延时才能读到真正电平
  15. VirtualBox下安装Ubuntu Server 16.04
  16. Invalid bound statement (not found) 找不到mapper 映射文件异常
  17. Linux使用curl 方式安装docker-compose 后执行docker-compose version 检查安装是否成功时出错的解决办法
  18. DCDC与LDO
  19. 耐克的定制页用canvas如何实现....跪求前端大神指点。
  20. C#--索引

热门文章

  1. 关于CPU核心,线程,进程,并发,并行,及java线程之间的关系
  2. log4j日志不输出的问题
  3. new的执行过程
  4. centos赋予访问权限
  5. tomcat 报错出现 jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
  6. mysql replace into使用
  7. Idea 配置Jrebel热部署
  8. Django基础五之django模型层之关联管理器
  9. 在ZYBO板卡上实现PL-PS交互(通过AXI的方式)
  10. postgresql从库搭建--逻辑复制