Exception handling try...except
When writing python code, sometimes the code may be wrong for some reasons-specific analysis of the specific reasons, we sometimes need to know the reason for the error to be more convenient to correct the error.
The following example illustrates the error in python
1. Syntax error
# 例1
if 2>1
print(2222)
# 例2
dic = {
"name";"alex"}
tu = (2,3,4''6)
# 错误提示:SyntaxError: invalid syntax
2. Logic error
dic = {
"name":"海狗","age":18}
dic["hobby"]
# 错误提示:KeyError: 'hobby'
Commonly used is if to perform abnormal judgment, but the following will use try as an example:
Single branch:
try:
num = int(input(">>>")) #出现value错误之后,直接跳转except语句
print(111)
except ValueError:
print(666)
# >>>a
# 666
try:
dic = {
"name":"嘉欣"}
print(dic["age"])
num = int(input(">>>")) # 出现value错误之后,直接跳转except语句
print(111)
except ValueError:
print(666)
# KeyError: 'age'
try:
dic = {
"name":"嘉欣"}
print(dic["age"])
num = int(input(">>>")) # 出现value错误之后,直接跳转except语句
print(111)
except KeyError:
print(666)
# 666
Multiple branches:
try:
num = int(input(">>>")) # 出现value错误之后,直接跳转except语句
dic = {
"name": "嘉欣"}
#print(dic["age"])
l1 = [1,2]
print(l1[100])
except ValueError:
print("输入的有非数字元素")
except KeyError:
print("没有此键")
except IndexError:
print("没有此下标")
print(666)
# >>>1233
# 没有此键
# 666
# >>>asd
# 输入的有非数字元素
# 666
# >>>123
# 没有此下标
# 666
One exception:
try:
dic = {
"name": "嘉欣"}
# print(dic["age"])
l1 = [1,2]
print(l1[100])
print(111)
for i in 123:
pass
except Exception as e: # Exception 会将错误报出来
print(e)
# 'age'
# list index out of range
# 'int' object is not iterable
When to use Magnum? When to use multiple branches?
If you don’t care about the error message, but just want to eliminate the error and let the program continue to run, use the universal exception
But generally write code...Don’t add try to every paragraph... Isn’t that worrying?
Multi-branch plus universal
def func():
pass
def func1():
pass
dic = {
1:func,
2:func1,
}
try:
num= int(input("请输入序号"))
dic[num]()
except ValueError:
print("请输入数字")
except KeyError:
print("请输入范围内的序号")
except Exception:
print("程序出现意料之外的错误....")
# 请输入序号456
# 请输入范围内的序号
# 请输入序号asfd
# 请输入数字
# 请输入序号1
try else finally structure:
try:
dic = {
"name": "嘉欣"}
#print(dic["age"])
l1 = [1,2]
# print(l1[100])
print(111)
except ValueError:
print("输入的有非数字元素")
except KeyError:
print("没有此键")
else:
print("如果没有出现异常则执行这里")
finally:
print("finally 666")
# 没有此键
# finally 666
# finally 666
# IndexError: list index out of range
# 111
# 如果没有出现异常则执行这里
# finally 666
# 如果将except都注释掉
try:
dic = {
"name": "嘉欣"}
# print(dic["age"])
l1 = [1,2]
# print(l1[100])
print(111)
# except ValueError:
# print("输入的有非数字元素")
# except KeyError:
# print("没有此键")
# else:
# print("如果没有出现异常则执行这里")
finally:
print("finally 666")
# 111
# finally 666
except must depend on try else must depend on except and try
finally only depend on try
finally: before the exception occurs, the execution of finally
finally is used to close the database connection, the file handle is closed, the data is saved, etc., the finally is used
with open("teat1",encoding="utf-8",mode="a+") as f1:
try:
for i in f1:
print(i)
if ....:
finally:
f1.close()
# SyntaxError: invalid syntax
def func():
try:
print(111)
return 666
finally:
print(22)
print(func())
# 111
# 22
# 666
Before the return end of the function, execute the finally code
while 1:
try:
print(1)
break
finally:
print(222)
# 1
# 222
Before break, execute finally code
Actively trigger an exception:
raise ValueError("出现了value错误")
# ValueError: 出现了value错误
Assertion: Show a tough attitude
name = "1"
n1 = input("请输入:")
assert name == n1
print(111)
print(222)
# 请输入:as
# AssertionError
#请输入:1
# 111
# 222
Custom exceptions:
There are many types of errors provided to you in python, but not all errors. Some errors require you to customize
class LiYeError(BaseException):
def __init__(self,msg):
self.msg=msg
def __str__(self):
return self.msg
try:
raise LiYeError('类型错误')
except LiYeError as e:
print(e)
# 类型错误
Above, I hope to help you~