Python中也有关于异常的处理
# 导入日志模块
import logging,sys #导入logging模块
logger = logging.getLogger("异常") #创建一个logger实例
filehadler = logging.FileHandler("mylog.txt") #创建一个日志记录文本
filehadler.formatter = logging.Formatter("%(name)s-%(asctime)s-%(levelname)s:%(message)s")
logger.addHandler(filehadler) #为logger实例添加处理器
# try:
# 2/int(input("number"))
# except BaseException as e:
# logger.exception(e)
# print("程序结束")
# 用raise 抛出异常
# try:
# str1 = input("number")
# if not str1.isnumeric():
# raise Exception("输入的是字母")
# if str1 == "0":
# raise Exception("输入的是零")
# except (ZeroDivisionError,TypeError,ValueError) as excep:
# print(excep)
# except Exception as e:
# print(e)
# print("程序结束")
# 异常处理
# try:
# num = 10
# num1 = int(input("请输入除数"))
# result = num1/num1
# print(result)
# except BaseException as e:
# print("baseException",e)
# except ValueError as e:
# print(e)
# else:
# print("正常结束")
# finally:
# print("关闭资源结束")
# 断言
# try:
# str1 ="ABCDEI" #调试程序时使用
# assert len(str1)>8,"密码长度不足8位"
# except AssertionError as e:
# print(e)
# 自定义异常
class MyException(BaseException):
msg = ""
def __init__(self,msg):
self.msg = msg
def getMessage(self):
return "异常信息-"+self.msg
#
# mye = MyException("aaaaaaaa")
# mye.getMessage()
try:
num = 0
if num == 0:
raise MyException("除数不能为0!")
2/num
except MyException as e:
print(e.getMessage())