try: print(a/b) except Exception as e: print("There is an exception") print(e) else: print("Lucky no exception") finally: print("Finally run out") print("Assure never die") ================================================== There is an Exception division by zero Finally run out Assure never die
异常有多种类别,这个异常就是 ZeroDivisionError,因此可以具体到
1 2 3 4 5 6 7 8 9 10 11 12 13
... except ZeroDivisionError as e: print("There is a ZeroDivisionError") print(e) except Exception as e: print("There is an exception") print(e) ... =================================================== There is a ZeroDivisionError division by zero Finally run out Assure never die
此时多个 except 并列,起到 if ...else if ... 的效果。
如果没有抛出异常,还可以跑 else 下面的语句。
1 2 3 4 5 6 7
a = 2 b = 1 =================================================== 2.0 Lucky no exception Finally run out Assure never die
还可以自己定义异常,暂时还没用到……
区别
两者都可以在测试中用到。断言的写法比较简洁,但只会提示错误,然后 go die。后者可以在异常发生时,继续处理程序。