python 自定义异常exception模块


方式1 - 定义成类使用

#1. 定义
from log import logger

class AsstException(Exception):
    def __init__(self, message):
        super().__init__(message)
        logger.error(message)


#2. 使用
from exception import AsstException

class Messenger(object):
    def __init__(self, sc_key):
        if not sc_key:
            raise AsstException('sc_key can not be empty')

方式2 - 直接assert使用

'''使用方法20200612
assert True # 条件为 true 正常执行
语法格式如下:
    assert expression
等价于:
    if not expression:
        raise AssertionError
'''
def is_existed(file_path):
    cursor.execute('SELECT COUNT(*) FROM photo WHERE path = ? AND existed = 1', (file_path,))
    row = cursor.fetchone()
    return row[0] != 0


assert not is_existed(temp_file)

方式3 - except 使用

# Python < 2.6
try:
      3/0
except Exception, e:
      print 'str(Exception):\t', str(Exception)       #输出  str(Exception):<type 'exceptions.Exception'>
      print 'str(e):\t\t', str(e)                      #输出 str(e):integer division or modulo by zero
      
# Python > 2.6
try:
      3/0
except Exception as e:
      print ('str(Exception):\t', str(Exception)  )     #输出  str(Exception):	 <class 'Exception'>
      print ('str(e):\t\t', str(e)  )                    #输出 str(e):		 division by zero



# except 多个
try:
  print(x)
except NameError:
  print("Variable x is not defined")
except: # except Exception as e的写法
  print("Something else went wrong")
  1. except捕获【多个】异常,列表【index error处理】
x= {'vesion': '05.R08;'}
try:
    print(x['rru_vesion'].split(';')[0].split(":")[1])
except (KeyError, IndexError) as e:
    print(e)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM