国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解在Python中處理異常的教程

2020-02-23 01:24:28
字體:
供稿:網(wǎng)友

什么是異常?

異常是一個事件,其中一個程序,破壞程序的指令的正常流的執(zhí)行過程中而發(fā)生的。一般情況下,當(dāng)一個Python腳本遇到一些情況不能處理,就拋出一個異常。異常是一個Python對象,它表示一個錯誤。

當(dāng)Python腳本拋出一個異常,它必須處理異常,否則將立即終止。
處理異常:

如果有可能會引發(fā)異常的一些可疑的代碼,就可以通過將可疑的代碼在一個try塊:保衛(wèi)你的程序。在try塊,包括以下情況except:語句,其次是代碼,作為優(yōu)雅的處理問題,盡可能塊。
語法

這里是try....except...else 塊的簡單語法:

try:  You do your operations here;  ......................except ExceptionI:  If there is ExceptionI, then execute this block.except ExceptionII:  If there is ExceptionII, then execute this block.  ......................else:  If there is no exception then execute this block. 

這里有一些關(guān)于上述語法要點:

    單個try語句可以有多個不同的語句。當(dāng)try塊中包含可能會引發(fā)不同類型的異常語句,這是很有用的。     也可以提供一個通用的except子句,它用來處理任何異常。     except子句后,可以包括其他子句。塊沒有引發(fā)異常:在別的塊中的代碼,如果在try中的代碼執(zhí)行。     在else塊是不需要try:塊的代碼的保護(hù)。

例子

這里是簡單的例子,這將打開一個文件并寫入內(nèi)容的文件中并移出正常:

#!/usr/bin/pythontry:  fh = open("testfile", "w")  fh.write("This is my test file for exception handling!!")except IOError:  print "Error: can/'t find file or read data"else:  print "Written content in the file successfully"  fh.close()

這將產(chǎn)生以下結(jié)果:

Written content in the file successfully

示例:

這里有一個更簡單的例子,它試圖打開沒有權(quán)限并在文件中寫入內(nèi)容,所以它會引發(fā)一個異常:

#!/usr/bin/pythontry:  fh = open("testfile", "r")  fh.write("This is my test file for exception handling!!")except IOError:  print "Error: can/'t find file or read data"else:  print "Written content in the file successfully"

這將產(chǎn)生以下結(jié)果:

Error: can't find file or read data

在except子句無異常:

還可以使用不同的定義如下無異常的聲明:

try:  You do your operations here;  ......................except:  If there is any exception, then execute this block.  ......................else:  If there is no exception then execute this block. 

try-except 語句捕獲所有出現(xiàn)的異常。使用這種try-except 聲明不被認(rèn)為是一個良好的編程習(xí)慣,但因為它捕獲所有異常,但不會使程序員找出可能出現(xiàn)的問題的根本原因。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 潼南县| 威远县| 昌宁县| 万荣县| 昌邑市| 永春县| 科技| 三亚市| 安泽县| 辰溪县| 广德县| 报价| 枞阳县| 西峡县| 北流市| 宽城| 辉南县| 襄城县| 怀安县| 外汇| 平凉市| 梓潼县| 休宁县| 黄梅县| 兴城市| 开远市| 临海市| 宣威市| 泽普县| 西青区| 康定县| 高唐县| 邵武市| 望江县| 财经| 上饶县| 三江| 浑源县| 玉环县| 肇东市| 绍兴县|