捕获多个指定异常
try:
print(1/0)
except (NameError, ZeroDivisionError):
print('有错误')
异常类型
print(1/0)
异常的传递
import time
try:
f = open('test.txt')
try:
while True:
con = f.readline()
if len(con) == 0:
break
time.sleep(3)
print(con)
except:
print('程序被意外终止')
except:
print('该文件不存在')
捕获指定异常
try:
print(1/0)
except NameError:
print('有错误')
捕获异常描述信息
try:
print(1/0)
except (NameError, ZeroDivisionError) as result:
print(result)
体验异常
"""
try:
可能发生错误的代码
except:
发生错误的时候执行的代码
"""
try:
f = open('test.txt', 'r')
except:
f = open('test.txt', 'w')
捕获所有异常
try:
print(num)
except Exception as result:
print(result)
自定义异常
class ShortInputError(Exception):
def \_\_init\_\_(self, length, min\_len):
self.length = length
self.min\_len = min\_len
def \_\_str\_\_(self):
return f'您输入的密码长度是{self.length}, 密码不能少于{self.min\_len}'
def main():
try:
password = input('请输入密码:')
if len(password) < 3:
raise ShortInputError(len(password), 3)
except Exception as result:
print(result)
else:
print('没有异常,密码输入完成')
main()
finally
try:
f = open('test100.txt', 'r')
except Exception as e:
f = open('test100.txt', 'w')
finally:
f.close()
else
try:
print(1)
except Exception as result:
print(result)
else:
print('我是else,当没有异常的时候执行的代码')
copy
import os
import re
def process\_py\_file(file\_path):
with open(file\_path, 'r',encoding='utf-8'
) as f:
content = f.read()
content = re.sub(r'([\_\*\`])', r'\\\1', content)
markdown\_content = f"\`\`\`python\n{content}\n\`\`\`"
return markdown\_content
def merge\_to\_markdown(directory, output\_md\_file):
with open(output\_md\_file, 'w',encoding='utf-8') as md\_file:
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.py'):
file\_path = os.path.join(root, file)
file\_title = file[:-3]
markdown\_content = process\_py\_file(file\_path)
index = file\_title.find('\_',4)
file\_title = file[index + 1:-3]
md\_file.write(f"# {file\_title}\n\n")
md\_file.write(markdown\_content)
md\_file.write('\n\n')
merge\_to\_markdown('D:\\ai\\ma\\阶段1-人工智能python基础\\day10-面向对象与异常处理\\day10-面向对象与异常处理\\02-代码', 'C:\\Users\\13020\\Desktop\\temp\\test.md')