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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 异常处理 库_python异常处理详解

發布時間:2023/12/31 python 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 异常处理 库_python异常处理详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本節主要介紹Python中異常處理的原理和主要的形式。

1、什么是異常

Python中用異常對象來表示異常情況。程序在運行期間遇到錯誤后會引發異常。如果異常對象并未被處理或捕獲,程序就會回溯終止執行。

2、拋出異常

raise語句,raise后面跟上Exception異常類或者Exception的子類,還可以在Exception的括號中加入異常的信息。

>>>raise Exception('message')

注意:Exception類是所有異常類的基類,我們還可以根據該類創建自己定義的異常類,如下:

class SomeCustomException(Exception): pass

3、捕捉異常(try/except語句)

try/except語句用來檢測try語句塊中的錯誤,從而讓except語句捕獲異常信息并處理。

一個try語句塊中可以拋出多個異常:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except ZeroDivisionError:

print "The second number can't be zero!"

except TypeError:

print "That wasn't a number, was it?"

一個except語句可以捕獲多個異常:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except (ZeroDivisionError, TypeError, NameError): #注意except語句后面的小括號

print 'Your numbers were bogus...'

訪問捕捉到的異常對象并將異常信息打印輸出:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except (ZeroDivisionError, TypeError), e:

print e

捕捉全部異常,防止漏掉無法預測的異常情況:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except :

print 'Someting wrong happened...'

4、else子句。除了使用except子句,還可以使用else子句,如果try塊中沒有引發異常,else子句就會被執行。

while 1:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

value = x/y

print 'x/y is', value

except:

print 'Invalid input. Please try again.'

else:

break

上面代碼塊運行后用戶輸入的x、y值合法的情況下將執行else子句,從而讓程序退出執行。

5、finally子句。不論try子句中是否發生異常情況,finally子句肯定會被執行,也可以和else子句一起使用。finally子句常用在程序的最后關閉文件或網絡套接字。

try:

1/0

except:

print 'Unknow variable'

else:

print 'That went well'

finally:

print 'Cleaning up'

6、異常和函數

如果異常在函數內引發而不被處理,它就會傳遞到函數調用的地方,如果一直不被處理,異常會傳遞到主程序,以堆棧跟蹤的形式終止。

def faulty():

raise Exception('Someting is wrong!')

def ignore_exception():

faulty()

def handle_exception():

try:

faulty()

except Exception, e:

print 'Exception handled!',e

handle_exception()

ignore_exception()

在上面的代碼塊中,函數handle_exception()在調用faulty()后,faulty()函數拋出異常并被傳遞到handle_exception()中,從而被try/except語句處理。而ignare_exception()函數中沒有對faulty()做異常處理,從而引發異常的堆棧跟蹤。

注意:條件語句if/esle可以實現和異常處理同樣的功能,但是條件語句可能在自然性和可讀性上差一些。

總結

以上是生活随笔為你收集整理的python 异常处理 库_python异常处理详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。