1. 程式人生 > >Python-異常處理

Python-異常處理

msg 其他 pri nal 類型 __init__ span 不存在 除法

一、捕獲異常

1、當程序出錯時,不會展示bug信息給用戶,而是提供一個友好的提示後,繼續執行程序

2、如下,實現除法,當分母為0時,捕獲並打印出異常信息;Exception可以捕獲任何異常

def div(x, y):
    try:
        print(x/y)
    except Exception as e:
        print(異常為, e)

>>> div(1,0)
異常為 division by zero

也可以指定異常為ZeroDivisionError

def div(x, y):
    try:
        print
(x/y) except ZeroDivisionError as e: print(異常為, e)

>>> div(1,0)
異常為 division by zero

3、同時捕獲多個異常

def fdiv(x,y):
    try:
        return x/y
    except TypeError as e:
        print(TypeError: , e)
    except ZeroDivisionError as e:
        print(ZeroDivisionError: , e)
    
except Exception as e: print(其他異常:, e)

>>> fdiv(‘ABC‘, 0)
TypeError: unsupported operand type(s) for /: ‘str‘ and ‘int‘
>>> fdiv(12,0)
ZeroDivisionError: division by zero

也可以用以下方式:

def fdiv1(x,y):
    try:
        return x/y
    except (TypeError, ZeroDivisionError, Exception) as e:
        
print(e)


>>> fdiv1(‘ABC‘, 0)
unsupported operand type(s) for /: ‘str‘ and ‘int‘
>>> fdiv1(12,0)
division by zero

二、常用異常

---------------IOError:打開文件路徑出錯或不存在------------------
try:
    f = open(error.txt,r)
except IOError as e:
    print(打開文件出錯, 錯誤信息:, e)

--------------ImportError:導入模塊路徑出錯或不存在--------------
try:
    import error
except ImportError as e:
    print(導入模塊出錯, 錯誤信息:, e)

--------------IndexError:索引出界----------------------------
list1 = [1,2,3,4,5,6]
try:
    print(list1[6])
except IndexError as e:
    print(查詢列表出錯, 錯誤信息:, e)

----------------keyError:查找字典中不存在的關鍵字---------------
dict1 = {1:A, 2:B}
try:
    print(dict1[3])
except KeyError as e:
    print(查詢字典出錯, 錯誤信息:, e)

----------------TypeError:參數類型不匹配----------------------
def fint(a):
    print(a/2)
try:
    str1 = ABC
    fint(str1)
except TypeError as e:
    print(參數類型出錯, 錯誤信息:, e)

------------ValueError:參數類型匹配,但是傳入的值不對------------
str1 = ABC
try:
    print(int(str1))
except ValueError as e:
    print(參數值出錯, 錯誤信息:, e)

------------------NameError:使用的變量沒有賦值------------------
try:
    print(a)
except NameError as e:
    print(參數出錯, 錯誤信息:, e)

三、自定義異常

class MyException(Exception):
    def __init__(self, msg):
        self.message = msg

    def __str__(self):
        return self.message

try:
    raise MyException(自定義異常)
except MyException as e:
    print(e)

四、主動拋出異常

try:
    raise IOError(讀寫文件出錯了)  #主動拋出IOError異常
except IOError as e:
    print(e)

五、try - except - else - finally

try:
    f = open(test.txt, r)
except IOError as e:  #打開文件失敗,則拋出異常
    print(e)
else:                 #打開文件成功,則執行else塊
    print(執行else)
    f.close()
finally:              #無論文件是否正常打開,都會執行finally塊
    print(執行finally)

Python-異常處理