Python中自定义异常

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())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值