while True: try: x = int(input("请输入一个数字")) print("输入的数字",x) if x == 88: print("退出程序") break except BaseException as e: print(e) print("异常,输入的不是一个数字") print("循环数字输入程序结束")
try: a = input("请输入一个被除数") b = input("请输入一个除数") c = float(a)/float(b) except BaseException as e: print(e) else: print(c) finally: print("我是finally中的语句,无论发生异常与否,都执行!") print("程序结束")
try: f = open("D:/r.txt","r") content = f.read() print(content) except: print("文件为找到") finally: print("run in finally.关闭资源") try: f.close() except BaseException as e: print(e) print("程序执行结束") with open("D:/r.txt","r") as h: c = h.readline() print(c) print("程序执行结束")
import traceback try: print("step1") num = 1/0 except: with open("D:/r.txt","a") as f: traceback.print_exc(file=f)
class AgeRrror(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 AgeRrror(age) else: print("正常的年龄",age)