`

python学习笔记9——第八章 异常

阅读更多

第八章  异常

 

1.

   (1)捕捉异常,try & except

>>> try:
	x = input("x: ")
	y = input("y: ")
	print x/y
except ZeroDivisionError:
	print "The second number can't be zero!"

	
x: 1
y: 0
The second number can't be zero!

 

   (2)捕捉异常并重新引发

>>> class MuffledCalculator:
	muffled = False;  #屏蔽开关的标志
	def calc(self, expr):
		try:
			return eval(expr)
		except ZeroDivisionError:
			if self.muffled:  #若屏蔽开着,则捕捉异常并进行处理
				print "Division by zero is illegal"
			else:  #若屏蔽关着,则捕捉异常并重新引发
				raise  #except捕捉到了异常,raise重新引发异常

			
>>> calculator = MuffledCalculator()
>>> calculator.calc('10/2')
5
>>> calculator.calc('10/0') #屏蔽机制未打开,因为muffled = False

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    calculator.calc('10/0') #屏蔽机制未打开,因为muffled = False
  File "<pyshell#26>", line 5, in calc
    return eval(expr)
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> calculator.muffled = True  #打开屏蔽机制
>>> calculator.calc('10/0')
Division by zero is illegal

 

   (3)多个except,捕捉多个不同类型的异常

>>> try:
	x = input("x: ")
	y = input("y: ")
	print x/y
except ZeroDivisionError:  
	print "Y can't be zero!"
except TypeError:
	print "That wasn't a numbber, was it?"

	
x: 1
y: 'test'
That wasn't a numbber, was it?

 

   (4)一个except捕捉多个类型异常,效果同(3)

>>> try:
	x = input("x: ")
	y = input("y: ")
	print x/y
except(ZeroDivisionError, TypeError, NameError):  #NameError找不到名字(变量)时引发
	print 'Your numbers were bogus(wrong)...'

 

   (5)捕捉异常对象,想让程序继续运行,又想记录错误时应用

>>> try:
	x = input("x: ")
	y = input("y: ")
	print x/y
except(ZeroDivisionError, TypeError), e:  #多个异常时也只需提供一个参数e,是一个元组
	print "Invalid input:", e

	
x: 1
y: 0
Invalid input: integer division or modulo by zero

x: 1
y: 'test'
Invalid input: unsupported operand type(s) for /: 'int' and 'str'

 

   (6)捕捉所有异常,except后不加东西

>>> try:
	x = input("x: ")
	y = input("y: ")
	print x/y
except:
	print "Something wrong happend..."

	
x: 
Something wrong happend...
>>> 

 

   (7) try & except & else

>>> while True:
	try:
		x = input("x: ")
		y = input("y: ")
		print 'x/y is', x/y
	except:
		print "Invalid input. Please try again."
	else:  #只有在异常没发生,也就是输入正确的时候,循环才退出
		break

	
x: 1
y: 0
x/y is Invalid input. Please try again.
x: 2
y: 'test'
x/y is Invalid input. Please try again.
x: 
Invalid input. Please try again.
x: 1
y: 2
 

   (8) try & finally, try & except & finally, try & except & else & finally

          --不管是否发生异常,finally语句块一定会执行

>>> try:
	1/0
except NameError:
	print "Unknown variable"
else:
	print "That went well!"
finally:
	print "Cleaning up."

 

   实例

>>> def describePerson(person):
	print "Description of", person['name']
	print 'Age:', person['age']
	try:
		print 'Occupation: ' + person['occupation']  #不能用逗号连接,若用逗号,则在异常发生前就打印了pccupation
	except KeyError:  #键不存在
		pass

>>> person = {'name': 'Sun', 'age': 32}
>>> describePerson(person)  #捕获异常并处理
Description of Sun
Age: 32
#如果最后一句为print 'Occupation:', person['occupation']
#则出现
>>> describePerson(person)
Description of Sun
Age: 32
Occupation:
#所以要用加号连接,不用逗号,防止在异常发生前就被打印。
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics