1. 程式人生 > >Python進階11 異常處理

Python進階11 異常處理

# encoding=utf-8
import socket
import urllib.request
import urllib.error
'''URLError
設定了超時時間是 1 秒,程式 1 秒過後伺服器依然沒有響應,於是丟擲了 URLError 異常,它屬於 urllib.error 模組,錯誤原因是超時。
'''
try:
    responseForTimeout = urllib.request.urlopen('http://httpbin.org/get', timeout=0.001)
except urllib.error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason, socket.timeout):
        print('TIME OUT')


try:
    response = urllib.request.urlopen('http://www.baidu.com/index.htm')
except urllib.error.URLError as e:
    print(e.reason)

'''程式沒有直接報錯,而是輸出瞭如上內容,這樣通過如上操作,我們就可以避免程式異常終止,同時異常得到了有效處理。'''

總結:

# 異常處理格式
try: ... except exception: ... else: ... finally: ...
# 丟擲異常
raise exception