Python处理异常机制
http://blog.chinaunix.net/u1/43502/showart_1134830.html [转载一篇好文章哈哈!]
分析一下python中的处理异常机制:
1.Python 使用 try...except 来处理异常,使用 raise 来引发异常。Java 和 C++ 使用 try...catch 来处理异常,使用 throw 来引发异常。
>>> try:
... fsock = open("/notthere")
... except IOError:
... print "The file does not exist, exiting gracefully"
... print "This line will always print"
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
如何来打印出来异常的具体信息呢?
try:
出现异常的模块
except 异常类型,error:
print error #表示的就是具体的异常信息了。通过error 进行显示出来的
具体的异常对象就是为error了哦!
至少3个方法:
----------------------------------
方法一:捕获所有异常
try
a=b
b=c
except Exception,ex:
print Exception,':',ex
--------------------------------------------------------------------------------
方法二:采用traceback模块查看异常
import traceback
try:
a=b
b=c
except:
traceback.print_exc()
--------------------------------------------------------------------------------
方法三:采用sys模块回溯最后的异常
import sys
try:
a=b
b=c
except:
info=sys.exc_info()
print info[0],':',info[1]
--------------------------------------------------------------------------------
把 traceback.print_exc() 打印在屏幕上的信息保存到一个文本文件中
try:
a=b
b=c
except:
f=open('c:\log.txt','a')
traceback.print_exc(file=f)
f.flush()
f.close()