python學習筆記(異常)

來源:互聯網
上載者:User

標籤:

什麼是異常

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

>>> 1/0

Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero
>>>

按自己的方式出錯raise語句

>>> raise Exception

Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception
Exception
>>> raise Exception(‘hyperdrive overload‘)

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
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 "<pyshell#6>", line 1, in <module>
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 <module>
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 "<pyshell#2>", line 1, in <module>
calculator.calc(‘10/0‘)#沒有屏蔽
File "F:/python/myDemo/except.py", line 5, in calc
return eval(expr)
File "<string>", line 1, in <module>
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 <module>
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 <module>
x=input(‘enter the first number: ‘)
File "<string>", 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 <module>
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 "<pyshell#1>", line 1, in <module>
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學習筆記(異常)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.