自定义异常:
class PxException(Exception): def __init__(self,msg): self.msg = msg def __str__(self): return self.msg
使用如上语法自定义异常
try: raise PxException('自定义我的异常') except PxException as e: print (e)
raise用于手动抛出异常
断言:
断言用于判断前面某个条件必须符合,如果不符合则通过断言终止.如下例子,如果 assert 判断 a == "test" 不成立,则代码直接中断运行,如果成立。什么都不做,接着执行下面的代码
a = "test"
try: assert a == "test" except PxException as e: print (e) else: print ("if no exception,run else") finally: print ("no matte if has exception,run finally ")