python之异常捕获及处理(try--except)
在python中,⾄少有两类错误,⼀种是程序语法错误,⼀种是程序异常。
所谓的语法错误是指你未按规定格式书写导致的错误,如:定义函数时,括号后⾯要紧跟英⽂冒号,若缺失则不能识别与运⾏,并抛
出 SyntaxError: invalid syntax错误
def exceptions()
print("语法错误")
"D:\Program Files\Python\" D:/demo/except_try.py
File "D:/demo/except_try.py", line 1
def exceptions()
^
SyntaxError: invalid syntaxpython的try和except用法
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\" 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中的异常
请参考⽂档
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\" 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\" 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\" D:/demo/except_try.py
程序发⽣某个不知道的异常:unsupported operand type(s) for +: 'int'and'str'
None
发⽣错误
None
Process finished with exit code 0
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\" 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\" 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\" 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\" 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\" 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\" 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
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论