Python基础教程(第2版)第八章 异常

1.异常

Python用异常对象来表示异常情况,遇到错误后,会引发异常

如果异常对象并未被处理或捕捉,程序就会用Traceback——一种错误信息终止执行

每个异常都是一些类的实例,这些实例可以被引发,并且可以用很多种方法进行捕捉,使得程序可以捉住错误井且对其进行处理,而不是让整个程序失败

2.引发异常

为了引发异常,可以使用一个类或者示例参数调用raise语句

        应该是Exception的子类

        使用类时,程序会自动创建实例

raise Exception('hyperdrive overload')
#异常提示:  	Traceback (most recent call last):
#				File "unit08.py", line 2, in <module>
#					raise Exception('hyperdrive overload')
#			Exception: hyperdrive overload

3.自定义异常类

直接或间接地继承Exception类或其他内建异常类

class SomeCustomException(Exception):
	pass

4.捕捉异常类

可以使用try/except来捕捉异常:

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

如果捕捉到了异常又想引发它(即传递异常,会终止程序),那么可以调用不带参数的raise:

class MuffledCaculator:
	muffled=False
	def calc(self,expr):
		try:
			return eval(expr)
		except ZeroDivisionError:
			if self.muffled:	#屏蔽机制打开时:打印错误信息
				print("Division by zero is illegal")
			else:	#屏蔽机制关闭时:ZeroDivisionError异常被捕捉但已经传递了
				raise
caculator=MuffledCaculator()
caculator.calc("10/0")	#Traceback (most recent call last):
#							File "unit08.py", line 29, in <module>
#								print(caculator.calc("10/0"))
#							File "unit08.py", line 22, in calc
#								return eval(expr)
#							File "<string>", line 1, in <module>
#						ZeroDivisionError: division by zero
caculator.muffled=True
print(caculator.calc("10/0"))	#Division by zero is illegal
								#None

5.捕捉多个异常类

可以使用多个except子句来捕捉多个异常:

try:
	x=10
	y="Hello,world!"
	print(x/y)
except ZeroDivisionError:
	print("The second number can't be zero!")
except TypeError:
	print("That wasn't a number,was it?")	#That wasn't a number,was it?

还可以将异常用元组列出

try:
	x=10
	y="Hello,world!"
	print(x/y)
except (ZeroDivisionError,TypeError,NameError):
	print("Your numbers were bogus...")		#Your numbers were bogus...

6.捕捉异常对象

如果发生了异常,程序会打印错误信息,但是继续运行

try:
	x=10
	y="Hello,world!"
	print(x/y)
except (ZeroDivisionError,TypeError) as e:
	print(e)	#unsupported operand type(s) for /: 'int' and 'str'

7.捕捉所有异常

如果想用一段代码捕捉所有异常,可以在except子句中忽略所有的异常类:

try:
	x=10
	y="Hello,world!"
	print(x/y)
except:
	print("Something wrong happened...")	#Something wrong happened...

8.else、Finally子句

使用else子句可以实现循环:

while True:
	try:
		x=int(input("Enter the first number:"))
		y=int(input("Enter the second number:"))
		value=x/y
		print("x/y is",value)
	except Exception as e:
		print("Invaild input:",e,"Please try again.")
	else:	#只有为引发异常时,才会退出循环,否则程序会不断要求重新输入
		break

Finally可以用来在可能的异常后进行清理:

        不管try子句中是否发生异常,finally子句一定会被执行

try:
	x=int(input("Enter the first number:"))
	y=int(input("Enter the second number:"))
	value=x/y
	print("x/y is",value)
except Exception as e:
	print("Invaild input:",e,"Please try again.")
finally:
	print("Cleaning up:")
	del x,y;

可以在同一条语句中组合使用try、except、finally和else

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值