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