简明python教程九----异常

使用try...except语句来处理异常。我们把通常的语句放在try-块中,而把错误处理语句放在except-块中。

import sys

try:
    s = raw_input(‘Enter something-->‘)
except EOFError:
    print ‘\nWhy did you do an EOF on me?‘
    sys.exit()
except:
    print‘\nSome error/exception occurred.‘

print ‘Done‘

结果:

==================== RESTART: D:/python_test/pickling.py ====================
Enter something-->

Why did you do an EOF on me?
>>>
==================== RESTART: D:/python_test/pickling.py ====================
Enter something-->
Done

把所有可能引发错误的语句放在try块中,然后在except从句/块中处理所有的错误和异常。

except从句可以专门处理单一的错误或异常,或者一组包括在圆括号内的错误/异常。

如果没有给出错误或者异常的名称,它会处理所有的错误和异常。

对于每个try从句,至少都有一个相关联的except从句。

如果某个错误或异常没有被处理,默认的python处理器就会被调用。它会终止程序的运行,并且打印一个消息。

还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。

引发异常:

可以使用raise语句引发异常,你需要指明错误/异常的名称和伴随异常触发的异常对象。你可以引发的错误和异常应该分别是一个Error或Exception类的直接或间接导出类。

class ShortInputException(Exception):
    ‘A user-defined exception class.‘
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length=length
        self.atleast=atleast

try:
    s=raw_input(‘Enter something-->‘)
    if len(s)<3:
        raise ShortInputException(len(s),3)
except EOFError:
    print ‘\nWhy did you do an EOF on me?‘
except ShortInputException,x:
    print ‘ShortInputException: The input was of length %d,\
        was expecting at least %d‘%(x.length,x.atleast)
else:
    print ‘No exception was raised.‘

结果:

==================== RESTART: D:/python_test/pickling.py ====================
Enter something-->

Why did you do an EOF on me?
>>>
==================== RESTART: D:/python_test/pickling.py ====================
Enter something-->ab
ShortInputException: The input was of length 2,        was expecting at least 3
>>>
==================== RESTART: D:/python_test/pickling.py ====================
Enter something-->abc
No exception was raised.

try...finally

假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件。我们可以使用finally块来完成。

注意,在一个try块下,你可以同时使用except从句和finally块,同时使用它们的时候,需要把一个嵌入另一个中

import time
try:
    f=file(‘poem.txt‘)
    while True:
        line = f.readline()
        if len(line)==0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print ‘Cleaning up...closed the file‘

结果:

programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Cleaning up...closed the file

说明:在每打印一行之前用time.sleep方法暂停2秒。程序在运行过程中,按Ctrl-c中断/取消程序。

我们可以回看到这样:

programming is fun
When the work is done
Cleaning up...closed the file

Traceback (most recent call last):
  File "D:/python_test/pickling.py", line 64, in <module>
    time.sleep(2)
KeyboardInterrupt

  KeyboardInterrupt异常被触发,程序退出。但在程序退出之前,finally从句仍然被执行,把文件关闭

时间: 2024-08-10 19:11:48

简明python教程九----异常的相关文章

简明 Python 教程:总结

 简明 Python 教程 说明:本文只是对<简明Python教程>的一个总结.请搜索该书查看真正的教程. 第3章 最初的步骤 1. Python是大小写敏感的. 2. 在#符号右面的内容都是注释 3. Python至少应当有第一行那样的特殊形式的注释.它被称作组织行——源文件的头两个字符是#!,后面跟着一个程序.这行告诉你的Linux/Unix系统当你执行你的程序的时候,它应该运行哪个解释器. #!/usr/bin/python 4. Linux/Unix用户适用:chmod命令用来改变文件

【转帖】简明 Python 教程

简明 Python 教程   下一页 简明 Python 教程 Swaroop, C. H. 著 沈洁元  译 版本:1.20 A Byte of Python Copyright © 2003-2005 Swaroop C H 简明 Python 教程 <简明 Python 教程>为 "A Byte of Python" 的唯一指定简体中文译本,版权 © 2005 沈洁元 本书依照 创作公用约定(署名-非派生作品-非商业用途) 发布. 概要 无论您刚接触电脑还是一个有经验

《简明Python教程》学习笔记

<简明Python教程>是网上比较好的一个Python入门级教程,尽管版本比较老旧,但是其中的基本讲解还是很有实力的. Ch2–安装Python:下载安装完成后,在系统的环境变量里,在Path变量后面追加安装目录的地址,即可在cmd下使用Python: CH3–Python3中,print的语法改为了print( ):Python编辑器列表:支持Python的IDE列表: CH4–变量不需要特别的变量类型定义过程: CH5–运算表达式及优先级: CH6–控制流,主控制语句行末以“:”结尾:if

[简明python教程]学习笔记2014-05-05

今天学习了python的输入输出.异常处理和python标准库 1.文件 通过创建一个file类的对象去处理文件,方法有read.readline.write.close等 [[email protected] 0505]# cat using_file.py #!/usr/bin/python #filename:using_file.py poem='''Programing is fun when the work is done use Python! ''' f=file('poem.

【转】简明 Python 教程

原文网址:http://woodpecker.org.cn/abyteofpython_cn/chinese/ 简明 Python 教程Swaroop, C. H. 著沈洁元  译www.byteofpython.info 版本:1.20 A Byte of Python Copyright © 2003-2005 Swaroop C H 简明 Python 教程 <简明 Python 教程>为 "A Byte of Python" 的唯一指定简体中文译本,版权 © 200

《简明 Python 教程》笔记

<简明 Python 教程>笔记 原版:http://python.swaroopch.com/ 中译版:https://bop.mol.uno/ 有 int.float 没 long.double.没 char,string 不可变. help 函数 如果你有一行非常长的代码,你可以通过使用反斜杠将其拆分成多个物理行.这被称作显式行连接(Explicit Line Joining)5: s = 'This is a string. \ This continues the string.'

简明Python教程笔记(二)----用户交互raw_input()

raw_input() python内建函数 将所有输入看做字符串,返回字符串类型 input()对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float ) input() 本质上还是使用 raw_input() 来实现的,只是调用完 raw_input() 之后再调用 eval() 函数 例子: #!/usr/bin/env pythonthis_year = 2014name = raw_input('please input your name:')age1 =

简明Python教程笔记(一)

#!/usr/bin/env python#Filename : helloworld.py#The use of 'and"  print 'hello,world!'print "hello,world!" #The use of '''and"""print '''This is a multi-line string. This is the first line.This is the second line."What's

简明 Python 教程中的第一个备份脚本

第一次学习python写的脚本 原为简明 Python 教程中的第一个脚本 原脚本如下 #!/usr/bin/python # Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/swaroop/byte', '/home/swaroop/bin'] # If you are u