你可以用raise语句来引发一个异常。异常/错误对象必须有一个名字,且它们应是Error或Exception类的子类。

raise the exception throw the exception by yourself

raise

if len(symbol) != 1 : 
    raise Exception('symbol need to be a string of length one')

try:
    raise Exception('出错了!!')
except Exception as e:
    print(e)
#结果
出错了!!
class InvalidPage(Exception):
    def __init__(self,data):
        self.data = data
try:
    raise InvalidPage('HAHA')

except InvalidPage as a:
    print('%s is a Invalid page'%a.data)

traceback

traceback.format_exc()

import traceback

try :
    raise Exception(' this is an error message')
except:
    errorfile = open('error_log.txt' ,'a')
    errorfile.write(traceback.format_exc())
    errorfile.close()
    print('the traceback info is wriiten to error_log.txt')

assertion

asert condition, 'error message'

assertions are for detecting programmer's error are not meant to be recovered, user's error should raise exceptions

results matching ""

    No results matching ""