什么是異常?
異常是一個事件,其中一個程序,破壞程序的指令的正常流的執(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)的問題的根本原因。
新聞熱點
疑難解答
圖片精選