python typeerror总结_python异常总结解析

对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误信息)终止执行:

>>> 1/0

Traceback (most recent call last):

File "",line 1,in

1/0

ZeroDivisionError: integer division or modulo by zero

raise 语句

为了引发异常,可以使用一个类(Exception的子类)或者实例参数数调用raise 语句。下面的例子使用内建的Exception异常类:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

>>> raise Exception #引发一个没有任何错误信息的普通异常

Traceback (most recent call last):

File "",in

raise Exception

Exception

>>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息

Traceback (most recent call last):

File "",in

raise Exception('hyperdrive overload')

Exception: hyperdrive overload

# End www.jb51.cc

系统自带的内建异常类:

>>> import exceptions

>>> dir(exceptions)

['ArithmeticError','AssertionError','AttributeError','BaseException','BufferError','BytesWarning','DeprecationWarning','EOFError','EnvironmentError','Exception','FloatingPointError','FutureWarning','GeneratorExit','IOError','ImportError','ImportWarning','IndentationError','IndexError','KeyError','KeyboardInterrupt','LookupError','MemoryError','NameError','NotImplementedError','OSError','OverflowError','PendingDeprecationWarning','ReferenceError','RuntimeError','RuntimeWarning','StandardError','StopIteration','SyntaxError','SyntaxWarning','SystemError','SystemExit','TabError','TypeError','UnboundLocalError','UnicodeDecodeError','UnicodeEncodeError','UnicodeError','UnicodeTranslateError','UnicodeWarning','UserWarning','ValueError','Warning','WindowsError','ZeroDivisionError','__doc__','__name__','__package__']

哇!好多,常用的内建异常类:

尽管内建的异常类已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。

和常见其它类一样----只是要确保从Exception类继承,不管直接继承还是间接继承。像下面这样:

>>> class someCustomExcetion(Exception):pass

当然,也可以为这个类添加一些方法。

捕捉异常

我们可以使用 try/except 来实现异常的捕捉处理。

假设创建了一个让用户输入两个数,然后进行相除的程序:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

#运行并且输入

Enter the first number: 10

Enter the second number: 0

Traceback (most recent call last):

File "I:/Python27/yichang",line 3,in

print x/y

ZeroDivisionError: integer division or modulo by zero

为了捕捉异常并做出一些错误处理,可以这样写:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except ZeroDivisionError:

print "输入的数字不能为0!"

#再来运行

>>>

Enter the first number: 10

Enter the second number: 0

# End www.jb51.cc

输入的数字不能为0! #怎么样?这次已经友好的多了

假如,我们在调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。那如何开启/关闭 “屏蔽”机制?

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

class MuffledCalulator:

muffled = False #这里默认关闭屏蔽

def calc(self,expr):

try:

return eval(expr)

except ZeroDivisionError:

if self.muffled:

print 'Divsion by zero is illagal'

else:

raise

#运行程序:

>>> calculator = MuffledCalulator()

>>> calculator.calc('10/2')

5

>>> calculator.clac('10/0')

Traceback (most recent call last):

File "",in

calculator.clac('10/0')

AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了

>>> calculator.muffled = True #现在打开屏蔽

>>> calculator.calc('10/0')

Divsion by zero is illagal

# End www.jb51.cc

多个except 子句

如果运行上面的(输入两个数,求除法)程序,输入面的内容,就会产生另外一个异常:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except ZeroDivisionError:

print "输入的数字不能为0!"

#运行输入:

>>>

Enter the first number: 10

Enter the second number: 'hello.word' #输入非数字

Traceback (most recent call last):

File "I:\Python27\yichang",line 4,in

print x/y

TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息

# End www.jb51.cc

好吧!我们可以再加个异常的处理来处理这种情况:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except ZeroDivisionError:

print "输入的数字不能为0!"

except TypeError: # 对字符的异常处理

print "请输入数字!"

#再来运行:

>>>

Enter the first number: 10

Enter the second number: 'hello,word'

# End www.jb51.cc

请输入数字!

一个块捕捉多个异常

我们当然也可以用一个块来捕捉多个异常:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except (ZeroDivisionError,TypeError,NameError):

print "你的数字不对!"

# End www.jb51.cc

捕捉全部异常

就算程序处理了好几种异常,比如上面的程序,运行之后,假如我输入了下面的内容呢

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

>>>

Enter the first number: 10

Enter the second number: #不输入任何内容,回车

Traceback (most recent call last):

File "I:\Python27\yichang",in

y = input('Enter the second number: ')

File "",line 0

^

SyntaxError: unexpected EOF while parsing

# End www.jb51.cc

晕死~! 怎么办呢?总有被我们不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

print x/y

except:

print '有错误发生了!'

#再来输入一些内容看看

>>>

Enter the first number: 'hello' * )0

# End www.jb51.cc

有错误发生了!

结束

别急!再来说说最后一个情况,好吧,用户不小心输入了错误的信息,能不能再给次机会输入?我们可以加个循环,保你输对时才结束:

# @param python异常大总结

# @author 编程之家 jb51.cc|jb51.cc

while True:

try:

x = input('Enter the first number: ')

y = input('Enter the second number: ')

value = x/y

print 'x/y is',value

except:

print '列效输入,再来一次!'

#运行

>>>

Enter the first number: 10

Enter the second number:

列效输入,再来一次!

Enter the first number: 10

Enter the second number: 'hello'

列效输入,再来一次!

Enter the first number: 10

Enter the second number: 2

x/y is 5

# End www.jb51.cc

总结

以上是编程之家为你收集整理的python异常总结解析全部内容,希望文章能够帮你解决python异常总结解析所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值