python异常处理演示

作者: admin 分类: Python 发布时间: 2022-12-25 09:43 浏览 67 次
import traceback

class NotChinaTelError(Exception):
    pass

class InvalidCharError(Exception):
    pass

def register():
    tel = input('请输入电话号码:')

    # 如果有非数字字符
    if not tel.isdigit():
        raise InvalidCharError

    # 如果不是以86开头,则不是中国号码
    if not tel.startswith('86'):
        raise NotChinaTelError

    return tel

try:
    ret = register()
except InvalidCharError:
    print('电话号码中有错误字符!')
     print(f'{traceback.format_exc()}')
except NotChinaTelError:
    print('非中国手机号码')
    print(f'{traceback.format_exc()}')

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续整理创作!

发表评论

邮箱地址不会被公开。 必填项已用*标注