1. 字符串为构造函数的参数
>> raise Exception('hyperdirve overload')Exception Traceback (most recent call last)in ()----> 1 raise Exception('hyperdrive overload')Exception: hyperdrive overload
又因为 Exception 是所有异常类的基类,因此所有的异常类都有一个接受字符串的构造函数。
2. 捕获多个异常
try: x, y = 1, 0. # x, y = 1, 'a' print(x/y)exception (ZeroDivisionError, TypeError), e: print(e.message)
在 python 3.x 中 exception 子句又可改造为:
exception (ZeroDivisionError, TypeError) as e: print(e.message)
3. 捕获所有异常
try: ...exception: print('Something wrong happened')
4. try … except … else
except… else… 与 if… else… 的执行逻辑是一致的,即 if(except) 发生 时,else 不再执行,而如果 if(except)判断不通过,将会进入 else 语句:
try: print('A simple test')except: print('WTF? Something went wrong.')else: print('Ah... Went just as planned.')
运行得如下输出:
A simple testAh... Went just as planned.