Python daily--sample of Exception

本文提供了两个Python异常处理的示例程序。第一个程序演示了如何处理输入过程中的异常情况,包括EOFError和其他未指定的异常。第二个示例展示了如何使用try-except-finally结构来确保文件操作的安全性,即使在出现异常的情况下也能正确关闭文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个异常处理的例子:

#!/usr/bin/python
# Filename: try_except.py

import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'

例子2 

#!/usr/bin/python
# Filename: finally.py

import time

try:

    f = file('\poem.txt')
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
except KeyboardInterrupt:
    print ('\nWhy did u do an EOF on me?')
finally:
    f.close()
    print('Cleaning up...closed the file')

执行结果:<当打印的时候点击ctrl+c>

>>> ================================ RESTART ================================
>>> 
sean
Why did u do an EOF on me?
Cleaning up...closed the file
>>> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值