5, exception handling, exception capture multiple, nested exception handling, an exception is thrown Custom
1) Exception Handling
try:
f = open('test.txt', 'r', True, 'GBK')
print(f.read())
except OSError as e:
print(e)
print(e.args) # 异常参数
print(e.errno) # 异常编号
print(e.strerror) # 异常描述信息
# 无论正常还是异常,finally 块总会执行,因此通常用于释放资源
finally:
if 'f' in globals(): # 当 f 变量存在时,关闭 f 文件流
f.close()
[Errno 2] No such file or directory: 'test.txt'
(2, 'No such file or directory')
2
No such file or directory
Analysis :
- If you need access exception information, use as abnormal specify a variable name, it can be omitted as clause.
2) Multi abnormal capture
Description : except block may capture a plurality of types of abnormality, a plurality of exception class enclosed in parentheses, separated by commas intermediate (construct multiple tuples exception class)
try:
a = int(input('请输入第一个整数:'))
b = int(input('请输入第二个整数:'))
print(a/b)
except (ValueError, ArithmeticError) as e:
print(e, type(e))
请输入第一个整数:a
invalid literal for int() with base 10: 'a' <class 'ValueError'>
请输入第一个整数:10
请输入第二个整数:0
division by zero <class 'ZeroDivisionError'>
Analysis : zero exception is the arithmetic exception classes
3) Exception Handling Nested
Description : Contains full exception handling flow in the try block, except the block or blocks finally exception handling nested condition is known.
f = None
try:
f = open('data.txt', 'r', True)
print(f.read())
except:
print('捕捉到异常')
finally:
if f: # f 不为 None 时关闭文件
try: # 在 finally 块中嵌套了异常处理
f.close()
print('关闭文件')
except:
print('关闭文件时有异常')
第一行
第二行
第三行
关闭文件
4) Custom throw an exception: raise
raise statement three common methods :
-
raise: The raise alone triggered the current caught exception, the default trigger abnormal RuntimeError
# 要求 age 必须在10到30岁之间 class User: def __init__(self,age=25): if age>30 or age<10: raise # 默认引发 RuntimeError 异常 self.__age = age def setage(self, age): if age>30 or age<10: raise # 默认引发 RuntimeError 异常 self.__age = age def getage(self): return self.__age age = property(fget=getage, fset=setage)
user = User(40)
RuntimeError: No active exception to reraise
user = User() user.age = 40
RuntimeError: No active exception to reraise
-
raise exception classes: with the raise an exception class, default instance of the specified initiator exception class
class User: def __init__(self,age=25): if age>30 or age<10: raise ValueError # 引发指定异常类的默认实例 self.__age = age def setage(self, age): if age>30 or age<10: raise ValueError # 引发指定异常类的默认实例 self.__age = age def getage(self): return self.__age age = property(fget=getage, fset=setage) user = User(40)
ValueError:
-
raise exception objects: caused by a specified exception object
class User: def __init__(self,age=25): if age>30 or age<10: raise ValueError(age, '年龄必须在10~30之间') # 引发指定的异常对象 self.__age = age def setage(self, age): if age>30 or age<10: raise ValueError(age, '年龄必须在10~30之间') # 引发指定的异常对象 self.__age = age def getage(self): return self.__age age = property(fget=getage, fset=setage) user = User(40)
ValueError: (40, '年龄必须在10~30之间')
Analysis : Combining capture abnormal use
class User:
def __init__(self,age=25):
if age>30 or age<10:
raise ValueError(age, '年龄必须在10~30之间') # 引发指定的异常对象
self.__age = age
def setage(self, age):
if age>30 or age<10:
raise ValueError(age, '年龄必须在10~30之间') # 引发指定的异常对象
self.__age = age
def getage(self):
return self.__age
age = property(fget=getage, fset=setage)
user = User(18)
print(user.age)
print('-'*30)
try:
user.age = 40
except ValueError as e:
print(e.args) # args 即创建异常对象时传入的参数
18
------------------------------
(40, '年龄必须在10~30之间')
5) else block
Description : no program exception occurs, the else block
try:
a = int(input('请输入第一个整数:'))
b = int(input('请输入第二个整数:'))
print(a/b)
except (ValueError, ArithmeticError) as e:
print(e, type(e))
else:
print('程序一切正常')
请输入第一个整数:10
请输入第二个整数:2
5.0
程序一切正常