四十二、python中異常

來源:互聯網
上載者:User

標籤:encode   import   str   對齊   environ   ror   exe   att   ted   



1.常用異常:
AttributeError 試圖訪問一個對象沒有的樹形,比如foo.x,但是foo沒有屬性x
IOError 輸入/輸出異常;基本上是無法開啟檔案
ImportError 無法引入模組或包;基本上是路徑問題或名稱錯誤
IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊
IndexError 下標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5]
KeyError 試圖訪問字典裡不存在的鍵
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個還未被賦予對象的變數
SyntaxError Python代碼非法,代碼不能編譯(個人認為這是語法錯誤,寫錯了)
TypeError 傳入物件類型與要求的不符合
UnboundLocalError 試圖訪問一個還未被設定的局部變數,基本上是由於另有一個同名的全域變數,
導致你以為正在訪問它
ValueError 傳入一個調用者不期望的值,即使值的類型是正確的

2.其他異常:
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
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
ZeroDivisionError

例子:
try:
l=[]
inp = input("請輸入:")
num = int(inp)
l[num]
except IndexError as e:
print("索引錯誤")
except Exception as e:
print("資料轉換錯誤")
print(e)


‘‘‘
3.異常其他結構
try:
# 主代碼塊
pass
except KeyError,e:
# 異常時,執行該塊
pass
else:
# 主代碼塊執行完,執行該塊
pass
finally:
# 無論異常與否,最終執行該塊
pass
try----出錯-----except--finally
try----未出錯---else---finally


4.主動出發異常

try:
print("123")
raise Exception("出錯了。。。")
except Exception as e:
#e 封裝了錯誤資訊的對象
print(e)


class Foo:
def __init__(self,arg):
self.arg=arg

def __str__(self):
return self.arg


obj=Foo(‘zhangyu‘)
print(obj)----------------------由於有__str__存在所以會輸出zhangyu,反之輸出的是對象
--------------------------------
zhangyu



5.斷言

assert 1==1

四十二、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.