异常捕获
try/except
try 语句按照如下方式工作:
-
执行 try 子句(在关键字 try 和关键字 except 之间的语句)。
-
如果没有异常发生,忽略 except 子句,try 子句执行后结束。
-
如果在执行 try 子句的过程中发生了异常,那么 try 子句余下的部分将被忽略。
-
如果异常的类型和 except 之后的名称相符,那么对应的 except 子句将被执行。一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
except只有第一个捕获的会执行。
一个except子句可以同时处理多个异常,这些异常将被放在一个括号里成为一个元组:
except (ValueError,IndexError) as e:
-
如果一个异常没有与任何的 except 匹配,那么这个异常将会传递给上层的 try 中。
Except多个异常
class AException(Exception):
def __str__(self):
return "A Exception"
class BException(AException):
def __str__(self):
return "B Exception"
class CException(AException, BException):
pass
Example 1
try:
try:
raise BException
except AException:
raise
except Exception as exc:
print("Raise exception")
print(str(exc))
# Raise exception
# B Exception
Example 2
try:
try:
raise BException
except AException:
raise AException
except Exception as exc:
print("Raise exception")
print(str(exc))
# Raise exception
# A Exception
Example 3
try:
exc_massage = []
try:
raise CException
except AException as exc:
exc_massage.append("AException")
raise exc
except BException as exc:
exc_massage.append("BException")
raise exc
except CException as exc:
exc_massage.append("CException")
raise exc
except CException:
print(exc_massage)
print("C Exception")
except AException as e:
print("A Exception")
except BException:
print("B Exception")
# ['AException']
# C Exception
try/except…else
try/except
语句还有一个可选的 else
子句,如果使用这个子句,那么必须放在所有的 except
子句之后。
else
子句将在 try
子句没有发生任何异常的时候执行。
使用 else
子句比把所有的语句都放在 try 子句里面要好,这样可以避免一些意想不到,而 except 又无法捕获的异常。
try:
try:
x = 1 / 0
except TypeError:
print("TypeError")
else:
print("Else")
except Exception as e:
print(e)
# division by zero
try/except…else…finally
finally 语句无论异常是否发生都会执行
Example 1
def test():
try:
print('try')
a = 1 / 0
print('try')
return 0
except:
print('except')
return 1
else:
print("else")
return 2
finally:
print('finally')
print(test())
# try
# except
# finally
# 1
Example 2
def test():
try:
print('try')
a = 5.0 / 0.0
print('try')
return 0
except:
print('except')
return 1
else:
print("else")
return 2
finally:
print('finally')
return 3
print(test())
# try
# except
# finally
# 3
Example 3
def test():
try:
print('try')
a = 1 / 1
print('try')
return 0
except:
print('except')
return 1
else:
print("else")
return 2
finally:
print('finally')
return 3
print(test())
# try
# try
# finally
# 3
Example 4
def test():
try:
print('try')
a = 1 / 1
print('try')
except:
print('except')
return 1
else:
print("else")
return 2
finally:
print('finally')
return 3
print(test())
# try
# try
# else
# finally
# 3