2016年12月19日 星期一

[Python]1.8 例外

動態語言中,除了語法錯誤造成的Syntax Error以外,幾乎所有的錯誤都來自執行期的錯誤.像是TypeError或是NameError等等.當錯誤發生時,Python會產生Traceback,方便檢視錯誤的來源. 但是在開發時,重要的不是辨識每一個錯誤而是排除掉一些不是錯誤的錯誤,例外. 舉個例子:
#有個檔案test_file.txt

3 4
1 3

20 19
%%%
88 7
1 2 3 
0
#使用try except 敘述來避開中間%%%的例外
f = open('/Users/lijack/Desktop/test_file.txt')
for lines in f:
    try:
        a , b = lines.strip().split()
        print "{:>2} + {:>2} ={:>3}".format(a,b,int(a)+int(b))
        
    except:
        pass
#python 不允許有suite是空白的
    
    
f.close


#strip()函數會移除字串頭尾指定的符號
string = "     12342342314213     "
print string.strip()

string1 = "8888888dfasfsdfsdafasdf888888"
print string1.strip('8')

#split函數:用特定字符切割字串
string2 = "hello world jack"
a,b,c = string2.split()
print a
print b
print c



















分析:如果沒有用try - except 敘述時,有幾行( %%%, 1 2 3)沒有符合兩個數字的形式,便會出現ValueError.如果用if -else 敘述時,會出現很多種複雜的狀況.但其實我們並不需要去處理跟我們需要不相關的事.

執行:我們先執行try的程式碼,當發生錯誤時,立刻停止try,進入except 執行suite 裡的程式碼(ex: pass),在這題等於我們略過了所有不符合規格的行.

沒有留言:

張貼留言