打印出异常信息
在 BaseException后面定义 msg 变量用于接收异常信息,通过print 将其打印出来 try:
open("abc.txt",'r') print aa except BaseException,msg: print msg 打印结果: >>> ================================ RESTART ================================ >>>[Errno 2] No such file or directory: 'abc.txt'
Python中常见的异常:
异常 描述BaseException 新的所有异常类的基类Exception 所有异常类的基类,但继承 BaseException 类AssertionError assert 语句失败AttributeError 试图访问一个对象没有属性IOError 输入输出异常,试图打一个不存的文件(包括其它情况)时引起NameError 使用一个还未赋值对象的变量IndexError 在使用序列中不存在的索引引发IndentationError 语法错误,代码没有正确的对齐KeyboardInterrupt Ctrl+C 被按下,程序被强行终止TypeError 传入的对象类型与要求不符SyntaxError Python 代码逻辑语法出错,不能执行 try...except 与 else配合使用 try: aa = ' 异常测试 ' print aa except Exception,msg: print msg else: print ' 没有异常! ' 打印结果: >>> ================================ RESTART ================================ >>> 异常测试 没有异常!说明:else 语句只有在没有异常的情况下才会被执行,但是有些情况下不管是否出现异常这些操作都能被执行,比如文 件的关闭,锁的释放,把数据库连接返还给连接池等操作。
Try...finally...语句---均会执行finally语句
首先我们来创建一个 poem.txt 文件。 pome.txt abc efg hijk lmn opq
下面我们通过一个小程序来读取文件中的内容。 import time files = file("poem.txt",'r') strs = files.readlines() try: for l in strs: print l
time.sleep(1)
finally: files.close() print 'Cleaning up ...closed the file'
第一次正常执行:
打印结果: >>> ================================ RESTART ================================ >>> abc efg hijk lmn opq Cleaning up ...closed the file 第二次按下ctrl+c终止执行:
打印结果: >>> ================================ RESTART ================================ >>> abc efg Cleaning up ...closed the file Traceback (most recent call last): File "F:\project\count.py", line 8, in <module> time.sleep(1) KeyboardInterrupt 抛出异常--- raise只能使用 Python 中所提供的异常类,自定义的异常类不起作用
对于 print 方法来说只能打印错误信息,Python中提供 raise 方法来抛出一个异常 filename = raw_input('please input file name:') if filename=='hello': raise NameError('input file name error !') 运行结果: >>> ================================ RESTART ================================ >>> please input file name:hello Traceback (most recent call last): File "F:\project\count.py", line 5, in <module> raise IOError('input file name error !') NameError: input file name error !