本文最后更新于 2022-05-26 11:25:30
exception
1 2 3 4 5 6 7 8 9 10
| try: <语句> except <名字>: <语句> except <名字>,<数据>: <语句> else: <语句> finally: <语句>
|
simple
1 2 3 4
| try: print(1/0) except ZeroDivisionError: print("不能除0")
|
多except
1 2 3 4 5 6
| try: print(1 / 0) except ZeroDivisionError: print(11111) except ValueError: print(222222)
|
不带任何异常类型
1 2 3 4 5
| try: print(1/0) except: print("不能除0")
|
带else
1 2 3 4 5 6 7
| try: pass except ZeroDivisionError: print(1) else: print("else")
|
带finally
1 2 3 4 5 6 7 8 9
| try: pass except ZeroDivisionError: print(1) else: print("else") finally: print("final")
|
带参数
1 2 3 4 5 6 7 8 9 10 11
| try: print(1 / 0) except ZeroDivisionError as e: print(e)
try: print(1 / 0) except ZeroDivisionError , e: print(e)
|
注意点


抛出异常
1 2 3 4
| def functionName( level ): if level < 1: raise Exception("Invalid level!", level)
|
自定义异常
1 2 3
| class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
|
10exception
https://jiajun.xyz/2020/10/29/python/01base/10exception/