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

一、异常处理语句

#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)
except ...

try:
    pass
except (Exception1, Exception2) as e:
    print(e)

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

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

二、自定义异常类

class MyException(Exception):
    pass

三、显式触发异常

raise
raise MyException
raise MyException()
raise MyException('Error')
raise MyException from None
raise MyException() from None

 

posted @ 2020-04-29 11:53  韩晓萌  阅读(727)  评论(0编辑  收藏  举报