try:
print('step1')
a = 3 / 0
print('step2')
except BaseException as e:
print('step3')
print(e)
print('end')
2. try_finally
def test01():
try:
a = input('被除数')
b = input('除数')
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print('我是finally语句,无论发生异常与否,都会执行')
print('程序结束!')
return 'e'
print(test01())
try:
f = open('a.txt', 'a', encoding='utf-8') # 这里让操作系统编写utf-8的文件,因此在python中打开就不会乱码了
s = '你好\n文件\n'
a = ['a\n','b\n']
f.write(a)
except BaseException as e:
print(e)
finally:
f.close() # 这里确保文件一定会关闭
3. raise 抛出异常
4. 自定义异常
class AgeError(Exception): # 继承exception类
def __init__(self,errorInfo):
Exception.__init__(self)
self.errorInfo = errorInfo
def __str__(self):
return '年龄错误'+str(self.errorInfo)+'应该在1-150之间'
if __name__ == '__main__': # 如果为True,则模块作为独立文件运行,可以执行测试代码
age = int(input('请输入一个年龄'))
if age < 1 or age > 150:
raise AgeError(age)
else:
print('正常年龄',age)
5. 常见异常的解决
6. with 上下文管理器
with open('e:/a.txt','r') as f:
content = f.readline()
print(content)
print('执行结束')