Python异常-try、raise语句及自定义异常类

一、try语句

#try/except
try:
    pass
except:
    pass

try:
    pass
except Exception:
    pass

#try/except...
try:
    pass
except (Exception1, Exception2):
    pass

try:
    pass
except Exception1:
    pass
except Exception2:
    pass

#try/except... as...
try:
    pass
except Exception as e:
    isinstance(e, Exception)
    
try:
    pass
except Exception1 as e1:
    isinstance(e1, Exception1)
except Exception2 as e2:
    isinstance(e2, Exception2)
    
try:
    pass
except (Exception1, Exception2) as e:
    print(e)

#try/except/else
try:
    pass
except ...:
    pass
else:
    pass
    
#try/finally
try:
    pass
finally:
    pass

try:
    pass
except ...:
    pass
finally:
    pass
    
try:
    pass
except ...:
    pass
else:
    pass
finally:
    pass

二、raise语句

raise
raise Exception
raise Exception()
raise Exception('Error')
raise Exception from None
raise Exception() from None

三、新建异常类

class MyException(Exception):
    pass

 

上一篇:Python 之关键字


下一篇:实现有状态对象或状态机