日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

【Python学习笔记】异常处理try-except

發(fā)布時(shí)間:2024/4/15 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python学习笔记】异常处理try-except 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python異常處理

我們一般使用try-except語句來進(jìn)行異常處理。

使用except Exception as err可以統(tǒng)一捕捉所有異常,而也可以分開處理單個(gè)異常。

# 分開捕捉單個(gè)異常try:num1 = int(input('Enter the first number:'))num2 - int(input('Enter the sencond number:'))print(num1 / num2) except ValueError: #捕捉數(shù)字轉(zhuǎn)化異常print('Please input a digit!') except ZeroDivisionError: #捕捉除0異常print('The second number cannot be zero')# 兩種異常一起捕捉try:num1 = int(input('Enter the first number:'))num2 - int(input('Enter the sencond number:'))print(num1 / num2) except (ValueError,ZeroDivisionError): print('Invalid input!')# 統(tǒng)一捕捉所有異常try:num1 = int(input('Enter the first number:'))num2 - int(input('Enter the sencond number:'))print(num1 / num2) except Exception as err:print('Something webt wrong!')print(err)

else語句

try-except還可以和else一起使用,如果語句中沒有異常引發(fā),那么這個(gè)else語句就會(huì)執(zhí)行。

try:num1 = int(input('Enter the first number:'))num2 - int(input('Enter the sencond number:'))print(num1 / num2) except (ValueError,ZeroDivisionError): print('Invalid input!') else:print('Aha, everything is OK.')

循環(huán)

如果我們想要用戶直到輸入正確,那么就要使用循環(huán),使用while True加上break語句

while True:try:num1 = int(input('Enter the first number:'))num2 - int(input('Enter the sencond number:'))print(num1 / num2)except (ValueError,ZeroDivisionError): print('Invalid input!')print('Aha, everything is OK.')

Finally語句

finally和else不一樣,不管有沒有異常引發(fā),finally語句都要執(zhí)行。

try:num1 = int(input('Enter the first number:'))num2 - int(input('Enter the sencond number:'))print(num1 / num2) except (ValueError,ZeroDivisionError): print('Invalid input!') finally:print('It is a finally clause.')

上下文管理器(Context Manager)和With語句

如果我們打開文件使用下面的代碼,在finally語句中,因?yàn)閒可能沒被成功定義,可能還是會(huì)報(bào)錯(cuò)。

try:f = open('data.txt')for line in f:print(line, end ='') except IOError:print('Cannnot open the file!') finally:f.close()

而我們可以使用下面的代碼打開文件,通過這個(gè)上下文管理器可以定義和控制代碼塊執(zhí)行前的準(zhǔn)備動(dòng)作及執(zhí)行后的收尾動(dòng)作。

with open('data.txt') as f:for line in f:print(line, end='')

轉(zhuǎn)載于:https://www.cnblogs.com/IvyWong/p/9802933.html

總結(jié)

以上是生活随笔為你收集整理的【Python学习笔记】异常处理try-except的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。