Python異常對象Exception基礎類異常捕捉

異常對象

Python中遇到錯誤後,會引發異常。

Python中使用異常對象來表示異常情況。

如果異常對象未被處理或者捕捉,程序就會用所謂的回溯(traceback)來終止執行。

下面是一個例子:

def func1():
    raise Exception
if __name__ == "__main__":
    func1()

執行之後報錯:

(venv) E:\Codes\python_everything\begining-python\src\08>list8-2.py
Traceback (most recent call last):
  File "E:\Codes\python_everything\begining-python\src\08\list8-2.py", line 19, in <module>
    func1()
  File "E:\Codes\python_everything\begining-python\src\08\list8-2.py", line 15, in func1
    raise Exception
Exception

異常有不同的類型,Exception是基礎類,下面還有各種子類:

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

還可以通過繼承Exception來實現自己的類:

class SomeError(Exception): pass
def func2():
    raise SomeError
if __name__ == "__main__":
    func2()

異常捕捉

異常可以被捕捉,需要使用try…except…語句:

class SomeError(Exception): pass
def func2():
    raise SomeError
if __name__ == "__main__":
    try:
        func2()
    except SomeError:
        print("Some error happened")

這裡捕捉到瞭參數,所以就不會回溯:

(venv) E:\Codes\python_everything\begining-python\src\08>list8-3.py
Some error happened

但是如果是其它的異常:

def func1():
    raise Exception
class SomeError(Exception): pass
def func2():
    raise SomeError
if __name__ == "__main__":
    try:
        func1()
    except SomeError:
        print("Some error happened")

這裡的Exception就沒有被捕獲,所以還是會回溯:

(venv) E:\Codes\python_everything\begining-python\src\08>list8-3.py
Traceback (most recent call last):
  File "E:\Codes\python_everything\begining-python\src\08\list8-3.py", line 27, in <module>
    func1()
  File "E:\Codes\python_everything\begining-python\src\08\list8-3.py", line 15, in func1
    raise Exception
Exception

如果沒有出現異常,則會繼續往下執行,但是這裡可以有else語句來執行沒有異常時可以執行的語句,使整個邏輯更通順:

if __name__ == "__main__":
    try:
        print("No exception")
    except SomeError:
        print("Some error happened")
    else:
        print("No error happened")

結果如下:

(venv) E:\Codes\python_everything\begining-python\src\08>list8-3.py
No exception
No error happened

但是有時即使發生瞭無法捕捉的異常,也想要執行一些語句,這個時候就可以使用finally語句:

def func1():
    raise Exception
class SomeError(Exception): pass
def func2():
    raise SomeError
if __name__ == "__main__":
    try:
        func1()
    except SomeError:
        print("Some error happened")
    else:
        print("No error happened")
    finally:
        print("Do something")

Python中更傾向於使用try…except…這樣的語句來代替if…else..語句。

以上就是Python異常對象異常捕捉及Exception基礎類的詳細內容,更多關於Python對象Exception類異常捕捉的資料請關註WalkonNet其它相關文章!

推薦閱讀: