python 之異常捕獲及處理(try--except)


在python中,至少有兩類錯誤,一種是程序語法錯誤,一種是程序異常。

所謂的語法錯誤是指你未按規定格式書寫導致的錯誤,如:定義函數時,括號后面要緊跟英文冒號,若缺失則不能識別與運行,並拋出 SyntaxError: invalid syntax錯誤

def exceptions()
    print("語法錯誤")

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
  File "D:/demo/except_try.py", line 1
    def exceptions()
                   ^ SyntaxError: invalid syntax

Process finished with exit code 1

而異常是指程序代碼書寫符合編碼規范,並能夠正常運行,但在運行時遇到錯誤並拋出,如:讓兩種不同類型進行運算,會拋出 TypeError

def add(x, y):
    """
    字符拼接
    :return:
    """
    str1 = x + y
    return str1


print(add(1, '3'))


"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
Traceback (most recent call last):
  File "D:/demo/except_try.py", line 13, in <module>
    print(add(1, '3'))
  File "D:/demo/except_try.py", line 10, in add
    str1 = x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Process finished with exit code 1

python中的異常

請參考文檔 https://docs.python.org/3/library/exceptions.html#bltin-exceptions

python中的異常捕獲及處理

程序運行出錯后將不再執行,若想程序忽略錯誤繼續執行,則要進行異常的捕獲處理操作,在python中用try ----- except語句進行異常的捕獲處理

# try --- except 語法
try:
    代碼1
    代碼2
except <異常>:
    代碼1
    代碼2

作用解析:當try下面的代碼發生異常時會進行匹配except 中的異常,若匹配上則執行except下面的語句,異常則處理完成;若未匹配上則程序終止並打印默認異常信息

     當try下面的代碼未發生異常時,不會匹配錯誤,程序正常往下執行。

用try --- except處理上個異常例子

1.捕獲異常后不做任何處理

def add(x, y):
    """
    字符拼接
    :return:
    """
    try:
        str1 = x + y
        return str1
    except TypeError:
        pass


print(add(1, '3'))

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
None

Process finished with exit code 0

2.將捕獲的異常打印處理

def add(x, y):
    """
    字符拼接
    :return:
    """
    try:
        str1 = x + y
        return str1
    except TypeError as e:
        print('程序發生異常:%s' % e)


print(add(1, '3'))

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
程序發生異常:unsupported operand type(s) for +: 'int' and 'str'
None

Process finished with exit code 0

3.有時可以預估會發生的錯誤類型,有時又會出現莫名奇妙的未在考慮范圍類的錯誤,這時可以用捕獲所有異常來處理(直接使用常見錯誤的基類Exception或不帶任何異常)

def add(x, y):
    """
    字符拼接
    :return:
    """
    try:
        str1 = x + y
        return str1
    # except常見錯誤的基類Exception
    except Exception as e:
        print('程序發生某個不知道的異常:%s' % e)


def zero(x, y):
    """
    除法
    :param x:
    :param y:
    :return:
    """
    try:
        return x/y
    # except不帶任何異常
    except:
        print("發生錯誤")

print(add(1, '3'))
print(zero(1, 0))

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
程序發生某個不知道的異常:unsupported operand type(s) for +: 'int' and 'str'
None
發生錯誤
None

Process finished with exit code 0

4.except后面帶多個異常,只要發生了其中一個異常,則進行處理

def zero(x, y):
    """
    除法
    :param x:
    :param y:
    :return:
    """
    try:
        return x/y
    # except帶多個異常
    except (TypeError, ValueError, ZeroDivisionError) as e:
        print("發生異常%s:" % e)


print(zero(1, 0))

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
發生異常division by zero:
None

Process finished with exit code 0

 5.使用多個except (如果多個 except 聲明的異常類型都與實際相匹配,最先匹配到的 except 會被執行,其他則被忽略)

try:
    a = 1/0 + data[2]

    print(a)
except TypeError as e:
    print(e)
except NameError as e:
    print(e)
except ZeroDivisionError as e:
    print(e)
except Exception as e:
    print(e)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
division by zero

Process finished with exit code 0

注意:當使用多個except時,最后一個最好能捕獲全部異常(except Exception)

try-----except -----else語句

try:
    語句
except (異常):
    語句
else:
    語句

解析:當try中發生異常時,進行匹配except錯誤,匹配上后執行except下的語句,且程序不會終止,若未匹配上程序終止並拋出異常

          當try中未發生異常時,則運行else下的語句

try:
    a = 3
except ZeroDivisionError:
    pass
else:
    print("I like %s" % a)

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
I like 3

Process finished with exit code 0

try----except ----finally語句

try:
    語句
except (異常):
  語句
finally: 語句

解析:不管try中有沒有發生異常最后都會執行finally下面的語句,且不受return語句影響

# 無異常演示
def open_file(file):
    try:
        f = open(file, 'r')
    except FileNotFoundError as e:
        print("文件不存在:%s" % e)
    except OSError as e:
        print("OS錯誤{}".format(e))
    except Exception as e:
        print("未知錯誤:%s" % e)
    finally:
        print("正在關閉文件")
        f.close()
open_file('D:/demo/except_try.py')

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
正在關閉文件

Process finished with exit code 0
# 異常演示
def open_file(file):
    try:
        f = open(file, 'r')
    except FileNotFoundError as e:
        print("文件不存在:%s" % e)
    except OSError as e:
        print("OS錯誤{}".format(e))
    except Exception as e:
        print("未知錯誤:%s" % e)
    finally:
        print("正在關閉文件")
        f.close()
open_file('D:/demo/try.py')

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
文件不存在:[Errno 2] No such file or directory: 'D:/demo/try.py'
正在關閉文件
Traceback (most recent call last):
  File "D:/demo/except_try.py", line 59, in <module>
    open_file('D:/demo/try.py')
  File "D:/demo/except_try.py", line 58, in open_file
    f.close()
UnboundLocalError: local variable 'f' referenced before assignment

Process finished with exit code 1
# 含return語句演示
def open_file(file):
    try:
        f = open(file, 'r')
    except FileNotFoundError as e:
        return "文件不存在:%s" % e
    except OSError as e:
        return "OS錯誤{}".format(e)
    except Exception as e:
        return "未知錯誤:%s" % e
    finally:
        print("正在關閉文件")
        f.close()
print(open_file('423'))

"D:\Program Files\Python\Python37-32\python.exe" D:/demo/except_try.py
Traceback (most recent call last):
  File "D:/demo/except_try.py", line 59, in <module>
    print(open_file('423'))
  File "D:/demo/except_try.py", line 58, in open_file
正在關閉文件
    f.close()
UnboundLocalError: local variable 'f' referenced before assignment

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM