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

巴壁虎 2020-04-29

一、异常处理语句

#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

相关推荐

快雪时晴天 / 0评论 2018-09-25