Enter x: 2
Enter y: 'a' # y 的输入是一个字符
----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-209-d4666cfaefb4> in <module>()
2 x = input('Enter x: ')
3 y = input('Enter y: ')
----> 4 print x / y
5 except ZeroDivisionError as e:
6 print e
TypeError: unsupported operand type(s) for /: 'int' and 'str'
try:
x = input('Enter x: ')
y = input('Enter y: ')
print x / y
except ZeroDivisionError as e: # 处理 ZeroDivisionError 异常
print 'ZeroDivisionError:',e
except TypeError as e: # 处理 TypeError 异常
print 'TypeError:',e
print 'hello world'
当 y 输入 'a' 时,看看执行结果:
Enter x: 3
Enter y: 'a'
TypeError: unsupported operand type(s) for /: 'int' and 'str'
hello world
捕捉未知异常
事实上,在编写程序的时候,我们很难预料到程序的所有异常情况。比如,对于第一个例子,我们可以预料到一个 ZeroDivisionError 异常,如果细心一点,也会预料到一个 TypeError 异常,可是,还是有一些其他情况我们没有考虑到,比如在输入 x 的时候,我们直接按回车键,这时又会引发一个异常,程序也会随之挂掉:
Enter x: # 这里输入回车键
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
因此,对于第一个例子,我们可以把程序做一些修改,使其更加健壮:
try:
x = input('Enter x: ')
y = input('Enter y: ')
print x / y
except ZeroDivisionError as e: # 捕获 ZeroDivisionError 异常
print 'ZeroDivisionError:',e
except TypeError as e: # 捕获 TypeError 异常
print 'TypeError:',e
except BaseException as e: # 捕获其他异常
print 'BaseException:',e
print 'hello world'
try:
x = input('Enter x: ')
y = input('Enter y: ')
print x / y
except ZeroDivisionError as e:
print 'ZeroDivisionError:',e
except TypeError as e:
print 'TypeError:',e
except BaseException as e:
print 'BaseException:',e
else:
print 'no error!'
print 'hello world'
看看执行结果:
Enter x: 6
Enter y: 2
3
no error!
hello world
finally 子句
finally 子句不管有没有出现异常都会被执行。
看看例子:
try:
x = 1/0
print x
finally:
print 'DONE'
执行结果:
DONE
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
再看一个例子:
try:
x = 1/0
print x
except ZeroDivisionError as e:
print 'ZeroDivisionError:',e
finally:
print 'DONE'
执行结果:
ZeroDivisionError: integer division or modulo by zero
DONE
使用 raise 手动引发异常
有时,我们使用 except 捕获了异常,又想把异常抛出去,这时可以使用 raise 语句。
看看例子:
try:
x = input('Enter x: ')
y = input('Enter y: ')
print x / y
except ZeroDivisionError as e:
print 'ZeroDivisionError:',e
except TypeError as e:
print 'TypeError:',e
except BaseException as e:
print 'BaseException:',e
raise # 使用 raise 抛出异常
else:
print 'no error!'
print 'hello world'
运行上面代码,当 x 输入一个回车键时,错误会被打印出来,并被抛出:
Enter x: # 这里输入回车键
BaseException: unexpected EOF while parsing (<string>, line 0)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing