python學習筆記(十五)異常處理

來源:互聯網
上載者:User

標籤:strip()   捕捉異常   字元   使用   final   字串   檢測   rod   遊標   

python解析器去執行程式,檢測到了一個錯誤時,觸發異常,異常觸發後且沒被處理的情況下,程式就在當前異常處終止,後面的代碼不會運行,所以你必須提供一種異常處理機制來增強你程式的健壯性與容錯性 。

例如,我們定義一個函數

first = input(‘請輸入除數:‘)second = input(‘請輸入被除數:‘)first = int(first)second = int(second)res = first/secondli = [1,2,3,4]print(li[5])

如果除數second=0,那代碼就會拋異常,ZeroDivisionError: division by zero,除數是不能為0的。

如果除數輸入是字串,那麼代碼也會拋異常,TypeError: unsupported operand type(s) for /: ‘int‘ and ‘str‘

這時就需要捕捉異常了,當除數為0時提示使用者所傳參數不對。異常處理使用的是try ....  except.....關鍵字。

first = input(‘請輸入除數:‘)second = input(‘請輸入被除數:‘)try:    first = int(first)    second = int(second)    res = first/secondexcept ValueError as e: #這個e代表錯誤資訊,如果上面的兩行代碼出現了 ValueError這個錯    print(e)    print(‘請輸入整數‘)except ZeroDivisionError as e:    print(e)    print(‘除數不能為0‘)

當異常種類很多的時候,我們可以統一寫為except Exception as e:

first = input(‘請輸入除數:‘)second = input(‘請輸入被除數:‘)try:    first = int(first)    second = int(second)    res = first/secondexcept Exception as e:   #上面代碼出異常的時候走這裡,    print(e)    print(‘出錯了。。。。。‘)
else: #沒有出錯,也不是必須寫的
print(‘並沒有出錯‘)#這個是沒有異常的時候走
print(res)
finally:#不管出錯或者沒有出錯都會執行它,也不是必須寫的。
print(‘我是finally‘)

現在我們完善一下操作資料庫的函數

1.資料庫在串連不成功時會拋異常

2.在執行sql的時候,如果sql語句寫的不正確也會拋異常

def my_db2(sql):    try:        coon = pymysql.connect( **MYSQL_INFO )    except Exception as res:        print(‘資料庫連接失敗了‘)        return ‘資料庫連接失敗了‘    cur = coon.cursor()  # 建立遊標    try:        cur.execute(sql)#執行sql    except Exception as res:        print(‘sql出錯,sql是%s‘%sql)        return ‘sql出錯‘    else:        if sql.strip()[:6].upper()==‘SELECT‘:            res =  cur.fetchall()        else:            coon.commit()            res = ‘ok‘    finally:        cur.close()        coon.close()    return res

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.