zoukankan      html  css  js  c++  java
  • python的异常处理

    一、 基本格式

    # 示例一:
    import requests
    try:     # 尝试进行下面操作,如果可以执行,就执行下面代码
        ret = requests.get('http://www.google.com')
        print(ret.text)
    except Exception as e:   # 如果不可以执行(平时会报错),这时不会报错,执行下面代码
        print('请求异常')   
    
    # 示例二:
    try:
        v = []
        v[11111]          # IndexError类型的异常
    except ValueError as e:   # ValueError是一个类,继承Exception,只能捕获到ValueError类型的异常
        pass
    except IndexError as e:   # IndexError是一个类,继承Exception,只能捕获到IndexError类型的异常
        pass
    except Exception as e:    # Exception是一个类,可以捕获到所有异常
        print(e)           # e是Exception类的对象,存储了一个错误信息
    
    • finally

      try:
          int('asdf')
      except Exception as e:
          print(e)
      finally:
          print('最后无论对错都会执行')
          
      # 特殊情况:
      def func():
          try:
              int('asdf')
          except Exception as e:
              return 123
          finally:
              print('最后')   # 无论对错,函数中遇到return,也会执行,执行完后再return
      
      func()
      
    • 建议:书写函数或功能时,建议用try包裹一下,避免报错

    • 示例

      # 1. 写函数,函数接受一个列表,请将列表中的元素每个都 +100
      def func(arg):
          result = []
          for item in arg:
              if item.isdecimal():
                  result.append(int(item) + 100)
      	return result 
      
      # 2. 写函数去,接受一个列表。列表中都是url,请访问每个地址并获取结果
      import requests 
      def func1(url_list):
          result = []
          try:
              for url in url_list:
                  response = requests.get(url)
                  result.append(response.text)
      	except Exception as e:
              pass
      	return result 
      
      def func2(url_list):
          result = []
          for url in url_list:
              try:
                  response = requests.get(url)
                  result.append(response.text)
              except Exception as e:
                  pass
      	return result 
      
      # 这两个函数执行结果是不一样的,是try所处的位置不同导致的
      func1(['http://www.baidu.com','http://www.google.com','http://www.bing.com'])
      func2(['http://www.baidu.com','http://www.google.com','http://www.bing.com'])
      

    二、 主动触发异常

    try:
        int('123')
        raise Exception('XXX')     # 代码中主动抛出异常
    except Exception as e:
        print(e)     # XXX
    
    • 示例:

      def func():
          result = True
          try:
              with open('x.log',mode='r',encoding='utf-8') as f:
                  data = f.read()
              if 'alex' not in data:
                  raise Exception()
          except Exception as e:
              result = False
          return result
      

    三、 自定义异常

    class MyException(Exception):    # 自定义异常,继承Exception
        pass
    
    try:
        raise MyException('asdf')    # 主动触发自定义异常,只有自定义异常自己和Exception能捕获到
    except MyException as e:
        print(e)
    
  • 相关阅读:
    003 python接口 cookies
    RocketDock 安装
    001 python接口 get请求
    mysql创建远程登陆用户并授权
    php时间函数
    ThinkPHP5高阶实战教程
    unset与unlink
    include 和require的区别
    80端口被system 占用
    【纪中受难记】——C2Day4:水题大赏
  • 原文地址:https://www.cnblogs.com/zengyi1995/p/10813214.html
Copyright © 2011-2022 走看看