第八章 異常

8.1 什麼是異常

異常對象未被處理或捕捉

8.2 按自己的方式出錯

8.2.1 raise:引發異常

>>> raise Exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception
>>> raise Exception('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: hello

內建異常類基本可以在exceptions模塊中找到,Exception爲所有異常的基類

>>> 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__']

8.2.2 自定義異常類

#創建異常類
class myException(Exception):
    pass

8.3 捕捉異常:try/except

>>> try:
...     x=1
...     y=0
...     print x/y
... except ZeroDivisionError:
...     print "The second number can't be zero!"
... 
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 "<stdin>", line 1, in <module>
  File "C:/Users/ZLin/Desktop/untitled0.py", line 92, in calc
    return eval(expr)
  File "<string>", line 1, in <module>

#屏蔽機制激活
>>> calculator.muffled=True
>>> calculator.calc('10/0')
Division by zero is illegal

8.4 不止一個except子句

try:
    ....
except xx:
    ...
except xx:
    ...

8.5 用一個塊捕捉兩個異常

try:
    ....
except(erro1,erro2...):
    ...

8.6 捕捉對象

try:
    ....
except(erro1,erro2...),e:#e爲一個元組,代表異常對象,erro1、erro2...
    print e
    ...

8.7 真正的全捕捉

try:
    ....
except:#捕捉任何異常。如果前面的異常沒有捕捉到,則這裏可以捕捉到
    ...

8.8 萬事大吉

try:
    ...
except:
    ...
else:#如果沒有異常發生
    ...

8.9 最後…..(真的?)

try:
    ....
except:
    ...
else:
    ...
finally:#不管有沒有異常,都會執行finally塊,主要做一些清理工作
    ...

8.10 異常之禪

if/else 和try/except

def print_info(person):
    #if/else
    if 'occupation' in person:
        print person[occupation]

    else:
        pass

    #try/except:不用去判斷
    try: 
        print person[occupation]#如果這句話沒有問題直接輸出
    except KeyError:
        pass

本章新函數

warning.filterwarnings(action…):過濾警告—感覺沒什麼大用處

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章