Python異常和異常處理

2022-07-30 07:57:13 字數 1069 閱讀 5311

python異常和異常處理

2023年12月20日 22:17:08 megustas_jjc 閱讀數:114 標籤: python 異常處理 更多

個人分類: python

while true:

filename = raw_input("please input a file to open:")

try:

datafile = open(filename)

except ioerror:

print "bad file name,try again"

else:

print "processing file",filename

processfile(datafile)

break #exit "while" loop(but do "finally" block first)

finally:

try:

datafile.close()

except nameerror:

print "going around again"

print "line after the try-except group"12

3456

78910

1112

1314

1516

1718

1920

2122

23深入異常——raise與自定義異常

(1)raise 任何時候都能引發異常,而不必等python來引發,只需要使用關鍵字raise加上異常的名稱

(2)自定義異常:

python中的異常是類,要建立異常,就必須建立其中乙個異常類的子類。通過繼承,將異常類的所有基本特點保留下來。例如下面例子,user引數需要是字串,並且僅由字母或數字組成,否則將會引發使用者自定義的異常:

class nameexception(exception):

print "name is error"

if not isinstance(user,str) or not user.isalnum():

raise nameexception

Python異常處理和異常型別

try some functions.except exception,e print e try some functions.except exception as e print e 注意這裡exception,e變成了exception as e 1.nameerror 嘗試訪問乙個未申明的...

python異常處理 Python 異常處理

使用者輸入不完整 比如輸入為空 或者輸入非法 輸入不是數字 異常就是程式執行時發生錯誤的訊號,在python中,錯誤觸發的異常如下 在python中不同的異常可以用不同的型別 python中統一了類與型別,型別即類 去標識,不同的類物件標識不同的異常,乙個異常標識一種錯 觸發indexerror 觸...

異常和異常處理

程式執行遇到兩種錯誤 1.error 錯誤 致命錯誤,無法恢復執行 2.exception 異常 通過修正,繼續執行。異常類常用方法 1.tostring 返回描述異常物件資訊字串 2.getmessage 返回描述物件詳細資訊 處理方法 1.try catch finally 1 try中包涵可能...