python 自定义异常

#custom_exception.py
class long_wait_error(Exception):
    def __init__(self,content):
        self.content=content
    def __str__(self):
        return self.content


#test.py
import time
import datetime
from .custom_exception import long_wait_error

t1=time.time()
tmp_content="等待 {} 消失超时".format("哈喽")
time.sleep(5)
t2=time.time()
if((datetime.datetime.fromtimestamp(t2)-datetime.datetime.fromtimestamp(t1)).seconds>3):
    raise long_wait_error(tmp_content)


macname@MacdeMacBook-Pro Desktop % python3 test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    raise long_wait_error(tmp_content)
custom_exception.long_wait_error: 等待 哈喽 消失超时
macname@MacdeMacBook-Pro Desktop % 



#test.py
import time
import datetime
from custom_exception import long_wait_error

t1=time.time()
tmp_content="等待 {} 消失超时".format("哈喽")
time.sleep(5)
t2=time.time()
while(1):
    if((datetime.datetime.fromtimestamp(t2)-datetime.datetime.fromtimestamp(t1)).seconds>3):
        raise long_wait_error(tmp_content)


macname@MacdeMacBook-Pro Desktop % python3 test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    raise long_wait_error(tmp_content)
custom_exception.long_wait_error: 等待 哈喽 消失超时
macname@MacdeMacBook-Pro Desktop % 
原文地址:https://www.cnblogs.com/sea-stream/p/14279930.html