Python異常處理和異常型別

2021-09-30 12:47:52 字數 2678 閱讀 8536

try:

...some functions...

except exception, e:

print(e)

try:

...some functions...

except exception

as e:

print(e)

注意這裡exception, e變成了exception as e

1. nameerror:嘗試訪問乙個未申明的變數

>>> v

nameerror: name 'v'

isnot defined

2. zerodivisionerror:除數為0
>>> v = 1/0

zerodivisionerror: int division or modulo by

zero

3. syntaxerror:語法錯誤
int

intsyntaxerror: invalid syntax (#14>, line 1)

4. indexerror:索引超出範圍
list = [2]

>>> list[3]

traceback (most recent call last):

file

"", line 1, in

list[3]

indexerror: list index out

ofrange

5. keyerror:字典關鍵字不存在
dic = 

>>> dic['3']

traceback (most recent call last):

file

"", line 1, in

dic['3']

keyerror

:'3'

6. ioerror:輸入輸出錯誤
>>> f = open('abc')

ioerror: [errno 2] no such file

ordirectory: 'abc'

7. attributeerror:訪問未知物件屬性
>>> 

class

worker:

defwork

(): print("i am working")

>>> w = worker()

>>> w.a

traceback (most recent call last):

file "", line 1, in

w.aattributeerror: 'worker' object has no attribute 'a'

8.valueerror:數值錯誤
>>> int('d')

traceback (most recent call last):

file "", line 1, in

int('d')

valueerror: invalid literal for

int() with base 10: 'd'

9. typeerror:型別錯誤
>>> istr = '22'

>>> ival = 22

>>> obj = istr + ival;

traceback (most recent call last):

file "", line 1, in

obj = istr + ival;

typeerror: can't convert 'int' object to str implicitly

10. assertionerror:斷言錯誤
>>> assert

1 != 1

traceback (most recent call last):

file "", line 1, in

assert

1 != 1

assertionerror

11.memoryerror:記憶體耗盡異常

12. notimplementederror:方法沒實現引起的異常

class

base

(object):

def__init__

(self):

pass

defaction

(self):

#丟擲異常,說明該介面方法未實現

raise notimplementederror

13. lookuperror:鍵、值不存在引發的異常

lookuperror異常是indexerror、keyerror的基類, 如果你不確定資料型別是字典還是列表時,可以用lookuperror捕獲此異常

14. standarderror 標準異常

除stopiteration, generatorexit, keyboardinterrupt 和systemexit外,其他異常都是standarerror的子類。

錯誤檢測與異常處理區別在於:錯誤檢測是在正常的程式流中,處理不可預見問題的**,例如乙個呼叫操作未能成功結束。

Python異常和異常處理

python異常和異常處理 2017年12月20日 22 17 08 megustas jjc 閱讀數 114 標籤 python 異常處理 更多 個人分類 python while true filename raw input please input a file to open try da...

Python 列舉型別和異常處理

使用列舉型別可以更加直觀的表示數值代表的意義 from enum import enum,unique unique 檢測重複 class color enum red 1 green 2 blue 3 c color.red print c color.red print c.red color....

python異常處理 Python 異常處理

使用者輸入不完整 比如輸入為空 或者輸入非法 輸入不是數字 異常就是程式執行時發生錯誤的訊號,在python中,錯誤觸發的異常如下 在python中不同的異常可以用不同的型別 python中統一了類與型別,型別即類 去標識,不同的類物件標識不同的異常,乙個異常標識一種錯 觸發indexerror 觸...