try-except

  1. try - except 語法如下:
    try:
    	You do your operations here;
    	......................
    except Exception:
    	If there is Exception, then execute this block.
    	......................
    
  2. 範例:使用 try - except 對 ZeroDivisionError 異常做處理。
    [dywang@dywmac zzz]$ cat except2.py
    #!/usr/bin/python
    # coding: utf-8
    
    def div(x, y):
    	try:
    		return x/y
    	except ZeroDivisionError:
    		print "除數不能為 0"
    
    print div(6, 2)
    print div(3, 0)
    print div(10,2)
    
  3. 執行結果:當除數為 0 時,輸出「除數不能為 0」,其中 None 為回傳值。
    [dywang@dywmac zzz]$ ./except2.py 
    3
    除數不能為 0
    None
    5