1 try:
2 x = input('Enter the first number: ')
3 y = input('Enter the second number: ')
4 print x/y
5 except ZeroDivisionError:
6 print "The second number can't be zero!"
7 except TypeError:
8 print "That wasn't a number, was it?"
一个except语句可以捕获多个异常:
1 try:
2 x = input('Enter the first number: ')
3 y = input('Enter the second number: ')
4 print x/y
5 except (ZeroDivisionError, TypeError, NameError): #注意except语句后面的小括号
6 print 'Your numbers were bogus...'
访问捕捉到的异常对象并将异常信息打印输出:
1 try:
2 x = input('Enter the first number: ')
3 y = input('Enter the second number: ')
4 print x/y
5 except (ZeroDivisionError, TypeError), e:
6 print e
捕捉全部异常,防止漏掉无法预测的异常情况:
1 try:
2 x = input('Enter the first number: ')
3 y = input('Enter the second number: ')
4 print x/y
5 except :
6 print 'Someting wrong happened...' 4、else子句。除了使用except子句,还可以使用else子句,如果try块中没有引发异常,else子句就会被执行。
1 while 1:
2 try:
3 x = input('Enter the first number: ')
4 y = input('Enter the second number: ')
5 value = x/y
6 print 'x/y is', value
7 except:
8 print 'Invalid input. Please try again.'
9 else:
10 break
上面代码块运行后用户输入的x、y值合法的情况下将执行else子句,从而让程序退出执行。 5、finally子句。不论try子句中是否发生异常情况,finally子句肯定会被执行,也可以和else子句一起使用。finally子句常用在程序的最后关闭文件或网络套接字。