异常
如果不希望程序停止执行,并且想要捕捉异常,那么我们可以按照 try/except 语句。
import math
while True:
try:
text = input('> ')
if text[0] == 'q':
break
x = float(text)
y = math.log10(x)
print("log10({0}) = {1}".format(x, y))
except ValueError:
print("the value must be greater than 0")
一旦 try 块中的内容出现了异常,那么 try 块后面的内容会被忽略,Python 会寻找 except 里面有没有对应的内容,如果找到,就执行对应的块,没有则抛出这个异常。
在上面的例子中,try 抛出的是 ValueError,except 中有对应的内容,所以这个异常被 except 捕捉到。
捕捉所有异常,将except 的值改成 Exception 类,来捕获所有的异常。
import math
while True:
try:
text = input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print("1 / log10({0}) = {1}".format(x, y))
except Exception:
print("invalid value")
指定特定异常
这里,我们把 ZeroDivisionError 加入 except 。
import math
while True:
try:
text = input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print("1 / log10({0}) = {1}".format(x, y))
except (ValueError, ZeroDivisionError):
print("invalid value")
或者另加处理:
import math
while True:
try:
text = input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print("1 / log10({0}) = {1}".format(x, y))
except ValueError:
print("the value must be greater than 0")
except ZeroDivisionError:
print("the value must not be 1")
将这两种方式结合起来,用 Exception 来捕捉其他的错误:
import math
while True:
try:
text = input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print("1 / log10({0}) = {1}".format(x, y))
except ValueError:
print("the value must be greater than 0")
except ZeroDivisionError:
print("the value must not be 1")
except Exception:
print("unexpected error")
为了得到异常的具体信息,我们将这个 ValueError 具体化:
import math
while True:
try:
text = input('> ')
if text[0] == 'q':
break
x = float(text)
y = 1 / math.log10(x)
print("1 / log10({0}) = {1}".format(x, y))
except ValueError as exc:
if exc.message == "math domain error":
print("the value must be greater than 0")
else:
print("could not convert '%s' to float" % text)
except ZeroDivisionError:
print("the value must not be 1")
except Exception as exc:
print("unexpected error:", exc.message)
else
try/except 块有一个可选的关键词 else。
如果使用这个子句,那么必须放在所有的 except 子句之后。else 子句将在 try 子句没有发生任何异常的时候执行。
try:
print(1)
except:
pass
else:
print('else was called.')
finally
try/except 块还有一个可选的关键词 finally。
不管 try 块有没有异常, finally 块的内容总是会被执行,而且会在抛出异常前执行,因此可以用来作为安全保证,比如确保打开的文件被关闭。
try:
print(1 / 0)
finally:
print('finally was called.')
如果异常被捕获了,在最后执行:
try:
print(1 / 0)
except ZeroDivisionError:
print('divide by 0.')
finally:
print('finally was called.')
警告
出现了一些需要让用户知道的问题,但又不想停止程序,这时候我们可以使用警告:
首先导入警告模块:
import warnings
def month_warning(m):
if not 1<= m <= 12:
msg = "month (%d) is not between 1 and 12" % m
warnings.warn(msg, RuntimeWarning)
month_warning(13)
有时候我们想要忽略特定类型的警告,可以使用 warnings 的 filterwarnings 函数:
filterwarnings(action, category)
将 action 设置为 ‘ignore’ 便可以忽略特定类型的警告:
warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)
month_warning(13)