Python自定义异常 Python Custom Exception

🍰 个人主页:__Aurora__
🍞如果文章有什么需要改进的地方还请各位大佬指正。
🍉如果我的文章对你有帮助➡️ 关注🙏🏻 点赞👍 收藏⭐️

请添加图片描述

一、python自定义异常

1.自定义一个CustomException类,继承Exception
请添加图片描述
2.编写CustomException类
输入一个大于0小于100的正整数数,否则报异常

class CustomException(Exception):
    min_e=0;
    max_e=100;
    def __init__(self,e,*args):
         super().__init__(args)
         self.e=e
    def __str__(self):
        return  f"This {self.e} does not meet the regulations"

3.编写触发异常的方法
当输入的正整数 大于100或者小于0 触发 CustomException异常

def customException_to(numberInput):
   if numberInput>CustomException.max_e or numberInput<CustomException.min_e:
       raise CustomException(numberInput)

最终代码

class CustomException(Exception):
    min_e=0;
    max_e=100;
    def __init__(self,e,*args):
         super().__init__(args)
         self.e=e
    def __str__(self):
        return  f"This {self.e} does not meet the regulations"
def customException_to(numberInput):
    if numberInput>CustomException.max_e or numberInput<CustomException.min_e:
        raise CustomException(numberInput)
if __name__ == '__main__':
    numberInput = input('Enter a temperature in Fahrenheit:')
    try:
       numberInput=int(numberInput)
       try:
           customException_to(numberInput)
       except CustomException as e:
           print(e)
    except ValueError as e:
        print(e)

测试结果
在这里插入图片描述

二、python自定义异常分析

1、字符串前的f

格式化 {} 内容,不在 {} 内的照常展示输出,如果你想输出 {},那就用双层 {{}} 将想输出的内容包起来。

lists = [1,2]
print(lists, f'lists length {len(lists)}.')
# [1, 2] lists length 2.

print(lists, f'lists length  {{len(lists)}}.')
#[1, 2] lists length  {len(lists)}.

print(lists, f'has a length of {{{len(lists)}}}.')#在 {} 内打印元素个数
# [1,2] has a length of {2}.

dics ={"name":"张三","age":18}
print(f'name of value  {dics.get("name")}.')
# name of value  张三.

2、 __init__(self,e,*args):

__init__方法接收参数e(可定义不同类型的多个形参)作为CustomException的属性

3、__str__属性

当触发异常时,需要异常信息。__str__方法返回自定义字符串

4、customException_to方法

customException_to方法的目的是判断达到报错条件,如果达到条件则通关键字raise触发CustomException

5、自定义代码执行顺序

输入999在这里插入图片描述
21行 接收999
23行 合法字符,整数
25行 执行customException_to方法
16-18行 判断输入numberInput,大于100则 触发CustomException异常
10-13行 初始化CustomException异常类
26行 捕捉异常,准备打印异常信息
14-15行获取异常信息
27行打印
在这里插入图片描述

参考:https://www.pythontutorial.net/python-oop/python-custom-exception/

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值