异常处理:
例1:
data1 = {}
data2 = []
try:
print(data2[1])
data1["name"]
except KeyError as e:
print("no key:", e)
except IndexError as e:
print("list index error:", e)
data1 = {}
data2 = []
try:
print(data2[1])
data1["name"]
except KeyError as e:
print("no key:", e)
except IndexError as e:
print("list index error:", e)
等同:
data1 = {}
data2 = []
try:
print(data2[1])
data1["name"]
except(KeyError, IndexError) as e:
print("no key:", e)
例2:except Exception 所有的错误都可以抓:不建议用
try:
print(data2[1])
data1["name"]
except Exception as e:
print("no key:", e)
例3:
data1 = {"name":"brace"}
data2 = [1,2]
try:
print(data2[1])
data1["name"]
except KeyError as e:
print("no key:", e)
except IndexError as e:
print("list index error:", e)
except Exception as e:
print("no key:", e)
else:
print("一切正常才执行")
finally:
print("不管有没错都执行")
自定义异常:
class BraceException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
raise BraceException("数据库连接不上!")
except BraceException as e:
print(e)
输出:
数据库连接不上!
class BraceException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return "XXXXXXXXXXXX"
try:
raise BraceException("数据库连接不上!")
except BraceException as e:
print(e)
输出:
XXXXXXXXXX
class BraceException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
raise BraceException("数据库连接不上!")
except BraceException as e:
print(e)
输出:
数据库连接不上!
class BraceException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return "XXXXXXXXXXXX"
try:
raise BraceException("数据库连接不上!")
except BraceException as e:
print(e)
输出:
XXXXXXXXXX