python 进阶 异常处理

  • 最简单的异常处理
    inp = input("请输入数字:")
    try:
        num = int(inp)
        print(num)
    except Exception as e:
        print("你输入的不是数字")
    # -------------------------------------------------------------
    li = []
    try:
        li = []
        li[999]
    
    # 捕捉多个异常,并进行处理
    except IndexError as e:
         print("索引错误")
    except ValueError as e:
        print("值错误")
    except Exception as e:
        print(e)
    
  • 手动触发异常
    try:
        print("123")
        raise Exception("出错了。。。")
    except Exception as e:
        # 封装错误信息的对象
        print(e)
    
    class MyException(Exception):
    
         def __init__(self, msg):
              self.message = msg
    
         def __str__(self):
              return self.message
         
     try:
         raise MyException("我的异常")
     except MyException as e:
     print(e)
    

你可能感兴趣的:(python 进阶 异常处理)