try结构?
try:
代码内容
except: # 有异常
print报错提示
else: # 没有异常
代码内容
finally:
无论如何都会被执行的内容
一般用来关闭try内容,节省资源
try:
a = int(input("被除数:"))
b = int(input("除数:"))
except ZeroDivisionError:
print("异常,不能除以0")
except ValueError:
print("不能将字符串转换为数字")
except NameError:
print("变量不存在")
except BaseException as e:
print(e)
print('异常')
else:
print(float(a)/float(b))
右键错误名可以查看diagram错误子类,以Zero为例: 
  
?
? 
with结构
# try写法
try:
f = open('D:/haha.txt','r')
print(f.readline())
except:
print("文件未找到")
finally:
try:
f.close()
except BaseException as e:
print(e)
# with写法
with open('D:/haha.txt','r') as f:
print(f.readline())
traceback结构
# 返回报错信息到指定路径文件
import traceback
try:
print(1/0)
except:
with open('D:/haha.txt','a') as f:
traceback.print_exc(file = f) # 不设置file则保存在默认路径
自定义异常类
# 命名一般用Error、Exception作后缀,继承Error、Exception
class AgeError(Exception):
def __init__(self, errorInfo)
Exception.__init__(self)
self.errorInfo = errorInfo
def __str__(self):
return str(self.errorInfo) + "Age Wrong, 应该在1-150"
# 测试代码
if __name__ == '__main__': # 如果为True,则模块作为独立文件运行,执行测试代码
age = int(input('Age:'))
if age<1 or age>150:
raise AgeError(age)
else:
print('Age:',age)
调试
- 断点
- 进入调试试图
- step over 按行执行,不进入子函数
- step into 按行执行
- step out 运行断点后所有代码
- run to cursor 执行到光标处
|