python中用来回溯异常的模块_python学习笔记(异常)
什么是異常
python用異常對(duì)象(exception?object)來表示異常情況。遇到錯(cuò)誤后,會(huì)引發(fā)異常。如果異常對(duì)象并未被處理或捕捉,程序就會(huì)用所謂的?回溯(Traceback,?一種錯(cuò)誤信息)終止執(zhí)行
>>> 1/0
Traceback (most recent call last):
File "", line 1, in
1/0
ZeroDivisionError: integer division or modulo by zero
>>>
按自己的方式出錯(cuò)
raise語句
>>> raise Exception
Traceback (most recent call last):
File "", line 1, in
raise Exception
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "", line 1, in
raise Exception('hyperdrive overload')
Exception: hyperdrive overload
>>>
查看exceptions模塊中的內(nèi)建異常
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
>>>
>>> raise ArithmeticError
Traceback (most recent call last):
File "", line 1, in
raise ArithmeticError
ArithmeticError
>>>
自定義異常類
盡管內(nèi)建的異常類已經(jīng)包括了大部分的情況,而且對(duì)于很多要求都已經(jīng)足夠了,但有些時(shí)候還是需要?jiǎng)?chuàng)建自己的異常類。
和常見其它類一樣----只是要確保從Exception類繼承,不管直接繼承還是間接繼承。像下面這樣:
>>> class SomeCustomException(Exception):
pass
當(dāng)然,也可以為這個(gè)類添加一些方法。
捕捉異常
我們可以使用?try/except?來實(shí)現(xiàn)異常的捕捉處理。
假設(shè)創(chuàng)建了一個(gè)讓用戶輸入兩個(gè)數(shù),然后進(jìn)行相除的程序:
x=input('Please enter the first number: ')
y=input('Please enter the second number: ')
print x/y
Please enter the first number: 10
Please enter the second number: 0
Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 3, in
print x/y
ZeroDivisionError: integer division or modulo by zero
>>>
為了捕捉異常并做出一些錯(cuò)誤處理,可以這樣寫:
try:
x=input('Please enter the first number: ')
y=input('Please enter the second number: ')
print x/y
except ZeroDivisionError:
print 'The second number can\'t be zero'
------------
Please enter the first number: 10
Please enter the second number: 0
The second number can't be zero
>>>
假如,我們?cè)谡{(diào)試的時(shí)候引發(fā)異常會(huì)好些,如果在與用戶的進(jìn)行交互的過程中又是不希望用戶看到異常信息的。那如何開啟/關(guān)閉?“屏蔽”機(jī)制?
class MuffledCalculator:
muffled=False
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print 'Division by zero is illegal'
else:
raise
------------
>>> calculator=MuffledCalculator()
>>> calculator.calc('10/2')
5
>>> calculator.calc('10/0')
Traceback (most recent call last):
File "", line 1, in
calculator.calc('10/0')#沒有屏蔽
File "F:/python/myDemo/except.py", line 5, in calc
return eval(expr)
File "", line 1, in
ZeroDivisionError: integer division or modulo by zero
>>> calculator.muffled=True
>>> calculator.calc('10/0')
Division by zero is illegal
>>>
不止一個(gè)except子句
如果運(yùn)行上面的(輸入兩個(gè)數(shù),求除法)程序,輸入面的內(nèi)容,就會(huì)產(chǎn)生另外一個(gè)異常:
enter the first number: 10
enter the second number: 'hello,world'
Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 4, in
print x/y
TypeError: unsupported operand type(s) for /: 'int' and 'str'
>>>
因?yàn)閑xcept子句只檢查ZeroDivisionError異常,所以這個(gè)異常就錯(cuò)過了檢查,為了捕捉這個(gè)異常,我們可以在try/except語句加一個(gè)except子句
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except ZeroDivisionError:
print 'The second number can\'t be zero'
except TypeError:
print 'That wasn\'t a number,was it?'
--------------------------
>>>
enter the first number: 10
enter the second number: 'hello,world!'
That wasn't a number,was it?
>>>
用一個(gè)塊捕捉兩個(gè)異常
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
捕捉對(duì)象
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except (ZeroDivisionError,TypeError,NameError),e:
print e
-----------------
>>>
enter the first number: 10
enter the second number: 2
5
>>>
>>> ================================ RESTART ================================
>>>
enter the first number: 10
enter the second number: 0
integer division or modulo by zero
>>> ================================ RESTART ================================
>>>
enter the first number: 10
enter the second number: 'hello,world'
unsupported operand type(s) for /: 'int' and 'str'
>>>
真正的全捕捉
就算程序能處理好幾種異常,但有些異常還是會(huì)處理不到,例如上個(gè)除法的例子,輸入空格:
enter the first number:
Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 2, in
x=input('enter the first number: ')
File "", line 0
^
SyntaxError: unexpected EOF while parsing
>>>
因此我們可以在except子句中忽略所有異常類
try:
x=input('enter the first number: ')
y=input('enter the second number: ')
print x/y
except:
print 'Something wrong happend...'
--------------
>>>
enter the first number: 10
enter the second number: 0
Something wrong happend...
>>> ================================ RESTART ================================
>>>
enter the first number:
Something wrong happend...
>>>
萬事大吉
while True:
try:
x=input('Enter the first number: ')
y=input('Enter the second number: ')
value=x/y
print 'x/y is ',value
except:
print 'Invalid input .Please try again.'
else:
break
--------------------
Enter the first number: 10
Enter the second number: 0
Invalid input .Please try again.
Enter the first number: 10
Enter the second number: 'hello'
Invalid input .Please try again.
Enter the first number: 10
Enter the second number: 2
x/y is 5
>>>
最后
最后finally子句用來對(duì)可能的異常進(jìn)行清理,它和try子句聯(lián)合使用
x=None
try:
x=1/0
finally:
print 'Cleaning up...'
del x
-------------
Cleaning up...
Traceback (most recent call last):
File "F:/python/myDemo/except.py", line 3, in
x=1/0
ZeroDivisionError: integer division or modulo by zero
>>>
try:
1/0
except NameError:
print 'Unknown variable'
else:
print 'That went well!'
finally:
print 'Cleaning up.'
異常和函數(shù)
如果異常在函數(shù)內(nèi)沒被處理,它就會(huì)傳播至函數(shù)調(diào)用的地方,直到程序帶著堆棧跟蹤終止
def faulty():
raise Exception('Someting is wrong')
def ignore_exception():
faulty()
def handle_exception():
try:
faulty()
except:
print 'Exception handled'
----------------------------
>>> ignore_exception()
Traceback (most recent call last):
File "", line 1, in
ignore_exception()
File "F:/python/myDemo/except.py", line 4, in ignore_exception
faulty()
File "F:/python/myDemo/except.py", line 2, in faulty
raise Exception('Someting is wrong')
Exception: Someting is wrong
>>> handle_exception()
Exception handled
>>>
總結(jié)
以上是生活随笔為你收集整理的python中用来回溯异常的模块_python学习笔记(异常)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle 合并重复数据_三天三夜整理
- 下一篇: python中classmethod的用