全部博文(2065)
分类: Python/Ruby
2009-02-10 10:54:24
>>> 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()
正确的异常组合格式如下:
1 正确的组合方式如下:
Try/except
Try/except/else
Try/finally
没有这种写法的哦:Try/except/finally
还可以像Java中的那样打印出来异常的具体的类型是什么的哦!~
num1 = raw_input('Enter a number:')
num2 = raw_input('Enter two number:')
try:
num1 = (float)(num1)
num2 = (float)(num2)
result = num1/num2
except ValueError,err: #这个就是异常的具体内容哦!
print err
#print
'number'
except ZeroDivisionError,e:
print '%s'%e
直接打印出来 这个异常的类型是什么的。
相当于JAVA中的try{}catch(Exception e)