日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中用来回溯异常的模块_python学习笔记(异常)

發布時間:2024/4/19 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中用来回溯异常的模块_python学习笔记(异常) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是異常

python用異常對象(exception?object)來表示異常情況。遇到錯誤后,會引發異常。如果異常對象并未被處理或捕捉,程序就會用所謂的?回溯(Traceback,?一種錯誤信息)終止執行

>>> 1/0

Traceback (most recent call last):

File "", line 1, in

1/0

ZeroDivisionError: integer division or modulo by zero

>>>

按自己的方式出錯

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模塊中的內建異常

>>> 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

>>>

自定義異常類

盡管內建的異常類已經包括了大部分的情況,而且對于很多要求都已經足夠了,但有些時候還是需要創建自己的異常類。

和常見其它類一樣----只是要確保從Exception類繼承,不管直接繼承還是間接繼承。像下面這樣:

>>> class SomeCustomException(Exception):

pass

當然,也可以為這個類添加一些方法。

捕捉異常

我們可以使用?try/except?來實現異常的捕捉處理。

假設創建了一個讓用戶輸入兩個數,然后進行相除的程序:

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

>>>

為了捕捉異常并做出一些錯誤處理,可以這樣寫:

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

>>>

假如,我們在調試的時候引發異常會好些,如果在與用戶的進行交互的過程中又是不希望用戶看到異常信息的。那如何開啟/關閉?“屏蔽”機制?

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

>>>

不止一個except子句

如果運行上面的(輸入兩個數,求除法)程序,輸入面的內容,就會產生另外一個異常:

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'

>>>

因為except子句只檢查ZeroDivisionError異常,所以這個異常就錯過了檢查,為了捕捉這個異常,我們可以在try/except語句加一個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?

>>>

用一個塊捕捉兩個異常

try:

x=input('enter the first number: ')

y=input('enter the second number: ')

print x/y

捕捉對象

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'

>>>

真正的全捕捉

就算程序能處理好幾種異常,但有些異常還是會處理不到,例如上個除法的例子,輸入空格:

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子句用來對可能的異常進行清理,它和try子句聯合使用

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.'

異常和函數

如果異常在函數內沒被處理,它就會傳播至函數調用的地方,直到程序帶著堆棧跟蹤終止

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

>>>

總結

以上是生活随笔為你收集整理的python中用来回溯异常的模块_python学习笔记(异常)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。