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

 

posted @ 2021-03-01 19:31  **绵绵羊**  阅读(3108)  评论(0编辑  收藏  举报