异常处理机制

>>> s = input('Enter something --> ') # before you entering something, press Ctrl + D
 Enter something --> 
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    s = input('Enter something --> ')
EOFError: EOF when reading a line
>>> 

看下面这段程序:

#!/usr/bin/env python
# Filename: try_except.py
import sys
import os
try:
    s = input('Enter something --> ') # before you entering something,press Ctrl+D
except EOFError:
    print(os.linesep + 'Why did you do an EOF on me?')
    sys.exit() # exit the program
# here, we are not exiting the program
print('Well done.')
执行结果1:

>>> ================================ RESTART ================================
>>> 
Enter something --> 


Why did you do an EOF on me?
Traceback (most recent call last):
  File "E:/myd/work/Python/try_except.py", line 9, in <module>
    sys.exit() # exit the program
SystemExit
>>> 
执行结果2:

>>> ================================ RESTART ================================
>>> 
Enter something -->  Python is exceptional!
Well done.

raise语句:

#!/usr/bin/env python
# Filename: raising.py
class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
try:
    s = input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
    # Other work can continue as usual here
except EOFError: # press Ctrl+D
    print('\nWhy did you do an EOF on me?')
except ShortInputException as x:
    print('ShortInputException: The input was of length %d, \
which was expecting at least %d' % (x.length, x.atleast))
else:
    print('No exception was raised.')
执行结果:

>>> ================================ RESTART ================================
>>> 
Enter something --> 

Why did you do an EOF on me?
>>> ================================ RESTART ================================
>>> 
Enter something --> 
ShortInputException: The input was of length 0, which was expecting at least 3
>>> ================================ RESTART ================================
>>> 
Enter something --> d
ShortInputException: The input was of length 1, which was expecting at least 3
>>> ================================ RESTART ================================
>>> 
Enter something --> Python
No exception was raised.
>>> 

finally语句

#!/usr/bin/env python
# Filename: finally.py
import os
import time
import sys
os.system('cd "E:\myd\work\Python"')
poem = ''' 
Programming is fun 
When the work is done 
if you wanna make your work also fun: 
use Python! 
'''  
f = open('poem.txt', 'w') # open for writing  
f.write(poem) # write text to file  
f.close()
try:
    f = open('poem.txt')
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2) # here you can press Ctrl+C to raise keyboard interruption
        sys.stdout.write(line)
finally:
    f.close()
    print('Cleaning up...closed the file')

输出:

>>> ================================ RESTART ================================
>>> 
 
Programming is fun 
When the work is done 
if you wanna make your work also fun: 
use Python! 
Cleaning up...closed the file
>>> ================================ RESTART ================================
>>> 
 
Programming is fun 
When the work is done 
Cleaning up...closed the file
Traceback (most recent call last):
  File "E:/myd/work/Python/finally.py", line 22, in <module>
    time.sleep(2) # here you can press Ctrl+C to raise keyboard interruption
KeyboardInterrupt
>>> 
呵呵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值