Python学习笔记之异常处理

Python异常处理

_ try _except语句

try:
    f = open("hello.txt", 'r')
    f.write("这是一个测试文件")
# 注意: except语句不一定会执行, 只有在try语句中出现IOError报错时, 才会执行.
except IOError as e:
    print('异常:',e)
# 如果没有捕获到异常, 则执行else语句的内容
else:
    print("文件内容写入成功")
# 无论是否捕获到异常, 都执行的语句.
finally:
    f.close()
    print("文件已经关闭")

在这里插入图片描述
不指定异常类型的except使用

try:
    f = open('hello.txt')
    # f.write("这是一个测试文件")
    f.write('cooffee')
# 不建议捕获所有的异常, 因能不能定位错误的位置.
except:
    print("捕获所有的异常....")
else:
    print("如果没有捕获到异常, 执行else语句")
finally:
    f.close()
    print("有异常或者没有异常都会执行")

在这里插入图片描述
捕获多个异常

try:
    d = dict(a=1, b=2)
    print(d['f'])  # KeyError
    print(a)  # NameError
except (KeyError, NameError) as e:
    print(e)
else:
    print("没有产生异常")
finally:
    print("无论是否产生异常的操作")
print("new start")

在这里插入图片描述
Try … Finally
假设你正在你的读取中读取一份文件。你应该如何确保文件对象被正确关闭,无论是否会发生异常?这可以通过 finally 块来完成。

import sys 
import time
f = None 
try:
    f = open("poem.txt") # 我们常用的文件阅读风格 
    while True:
        line = f.readline() 
        if len(line) == 0: 
        	break 
        print(line, end='')
        sys.stdout.flush()
        print("Press ctrl+c now") # 为了确保它能运行一段时间 
        time.sleep(2) 
 except IOError:
    print("Could not find file poem.txt") 
 except KeyboardInterrupt:
    print("!! You cancelled the reading from the file.") 
 finally: 
 	if f:
    	f.close()
    print("(Cleaning up: Closed the file)")
$ python exceptions_finally.py
Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)

我们按照通常文件读取进行操作,但是我们同时通过使用 time.sleep 函数任意在每打印一行后插入两秒休眠,使得程序运行变得缓慢(在通常情况下 Python 运行得非常快速)。当程序在处在运行过过程中时,按下 ctrl + c 来中断或取消程序。

你会注意到 KeyboardInterrupt 异常被抛出,尔后程序退出。不过,在程序退出之前,finally 子句得到执行,文件对象总会被关闭。

另外要注意到我们在 print 之后使用了 sys.stout.flush(),以便它能被立即打印到屏幕上。

with 语句
在 try 块中获取资源,然后在 finally 块中释放资源是一种常见的模式。因此,还有一个 with 语句使得这一过程可以以一种干净的姿态得以完成。

with open("poem.txt") as f: 
	for line in f:
        print(line, end='')

程序输出的内容应与上一个案例所呈现的相同。本例的不同之处在于我们使用的是 open 函数与 with 语句——我们将关闭文件的操作交由 with open 来自动完成。

在幕后发生的事情是有一项 with 语句所使用的协议(Protocol)。它会获取由 open 语句返回的对象,在本案例中就是“thefile”。

它总会在代码块开始之前调用 thefile.enter 函数,并且总会在代码块执行完毕之后调用 thefile.exit

因此,我们在 finally 代码块中编写的代码应该格外留心 exit 方法的自动操作。这能够帮助我们避免重复显式使用 try…finally 语句。

抛出异常
raise: 关键字, 用来抛出异常.
raise 抛出异常的名称, 抛出异常的详细显示
自定义异常类

class ShortInputException(Exception):
 	'''一个由用户定义的异常类''' 
 	def __init__(self, length, atleast): 
 		Exception.__init__(self)
        self.length = length
        self.atleast = atleast 
    try : 
    	text = input('Enter something --> ') 
        if len(text) < 3: 
        	raise ShortInputException(len(text), 3) # 其他工作能在此处继续正常运行 
    except EOFError: 
        print('Why did you do an EOF on me?') 
    except ShortInputException as ex:
        print(('ShortInputException: The input was ' + '{0} long, expected at least {1}').format(ex.length, ex.atleast)) 
    elseprint('No exception was raised.')
$ python exceptions_raise.py
Enter something --> a
ShortInputException: The input was 1 long, expected at least 3

$ python exceptions_raise.py
Enter something --> abc
No exception was raised.

断言assert
assert 语句 如果这个语句为真则通过,为假则报错

def is_huiwen_num(num):
    snum = str(num)
    return snum == snum[::-1]
# 如果希望程序中的所有assert语句不执行, 那么给python -O 脚本名
if __name__ == "__main__":
    assert is_huiwen_num(100) == True, "error"
    assert  is_huiwen_num(101) == True
    print("assert")

在这里插入图片描述
(以上转载自他人,便于自己学习记录)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值