Python 之try...except...錯誤捕捉

來源:互聯網
上載者:User

標籤:lib   __name__   print   布爾   列印   indexer   open   執行   int   


匯入:
lib下面的模組檔案可以直接匯入,如果不是就要指明路徑
import class_test #具體到模組名
class_test.add(2, 5)

import 具體到函數名
from class_test import add, sub, ...
add(5, 6)

測試代碼 放在if下面
if __name__ == ‘__main__‘: #執行程式的主入口
print("今天天氣不錯!") # 只有當你在當前模組下執行代碼的時候才會執行這裡面的代碼


import time
time.sleep(4)


Python代碼裡的異常處理
異常:代碼啟動並執行時候報錯
如果不處理,後續的程式就中斷了

1. 最簡單的用法 try ... except
try: 放你覺得有問題的代碼,放監控代碼
except 捕捉錯誤並進行處理
第一種用法:捕捉錯誤,不進行處理
try:
print(a)
except: # 捕捉錯誤
pass # pass 啥都不做,忽略,放生
print("hello, world")

第二種用法:對錯誤進行簡單的處理
try:
print(a)
except:
print("error!!!") 捕捉錯誤後報錯
print("hello, world")

第三種用法:列印出具體的錯誤
try:
print(a)
except Exception as e: #中央空調
print("出錯了:%s" % e)
print("hello, world")

NameError()

try:
print(a)
except NameError as e: # 小太陽
print("出錯了:%s" % e)
print("hello, world")


第四種用法:try...except...finally
try:
print(a)
except IndexError as e: # 小太陽
print("出錯了:%s" % e)
finally: #無論是否能捕捉到錯誤,finally後面的程式都運行
print("hello, world")

# 用途:一般我們用在檔案或資料庫資源的處理
try:
file = open(‘test.txt‘, ‘w‘)
file.read()
except Exception as e:
print("出錯了:%s" % e)
finally:
file.close()

第五種用法:try...except...else
try:
a = 4
b
except Exception as e:
print("出錯了:%s" % e)
else: # 只有當try不報錯的時候,才會繼續執行
print(a)

# 第五種用法
# 上下文管理器 with...as
with open("test.txt", ‘w‘) as file:
file.write("今天天氣真好")
print("with代碼內", file.closed)
print(file.closed) # 布爾值
# 什麼時候用? mysql, txt檔案資源

 

Python 之try...except...錯誤捕捉

聯繫我們

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