第十章 異常處理,異常處理

來源:互聯網
上載者:User

第十章 異常處理,異常處理

1.異常

  異常時程式運行時發生錯誤的訊號(在程式錯誤時,則會產生一個異常,若程式沒有處理,則會拋出該異常,程式的運行也隨之終止)

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

2.異常處理

  如果錯誤發生的條件是可預知的,需要用if進行處理,在錯誤發生之前進行預防

  如果錯誤發生的條件是不可預知的,則需要用try...except,在錯誤發生之後進行處理

try:    被檢測的代碼except 異常類型:    一旦檢測到該類型的異常,則執行這個位置的邏輯
try:    l=[]    print(l[111])except IndexError:    print('下標索引超出序列邊界')
try:    l=[]    print(l[111])except IndexError as e:   #擷取異常值    print(e)
try:    d={}    print(d['k'])except IndexError as e:    #可以寫多個except捕獲異常    print(e)except KeyError as e:      #可以寫多個except捕獲異常    print(e)
try:    d={}    print(d['k'])except Exception as e:      #萬能異常,可以捕獲所有異常    print(e)
try:    d={}    print(d['k'])except Exception as e:          print(e)else:    print('沒有異常')       #沒有異常的時候觸發finally:    print('結束')          #有無異常都觸發
stus=[]try:    if len(stus) == 0:        raise TypeError('列表元素為0')   #主動觸發異常except Exception as e:    print(e)
#stus=[]stus=['1']assert len(stus) > 0    #斷言,符合斷言則執行後面的代碼,不符合則拋出異常print('大於0')
class MyException(BaseException):    def __init__(self,msg):        super(MyException,self).__init__()        self.msg=msg    def __str__(self):        return '<%s>'%self.msgraise MyException('自訂異常')

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.