PHP前端开发

关于python中异常的详细说明

百变鹏仔 3周前 (02-08) #Python
文章标签 详细说明

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


&gt;&gt;&gt; 1/0Traceback (most recent call last):  File "<pyshell>", line 1, in <module>    1/0ZeropisionError: integer pision or modulo by zero</module></pyshell>

异常处理

捕捉异常可以使用try/except语句。

&gt;&gt;&gt; def inputnum():    x=input('Enter the first number: ')    y=input('Enter the first number: ')    try:        print x/y    except ZeroDivisionError:        print "The second number can't be zero"        &gt;&gt;&gt; inputnum()Enter the first number: 10Enter the first number: 0The second number can't be zero

raise 触发异常

&gt;&gt;&gt; class Muff:    muffled=False    def calc(self,expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.muffled:                print 'Division by zero is illegal'            else:                raise            &gt;&gt;&gt; c=Muff()&gt;&gt;&gt; c.calc(10/2)Traceback (most recent call last):  File "<pyshell>", line 1, in <module>    c.calc(10/2)  File "<pyshell>", line 5, in calc    return eval(expr)TypeError: eval() arg 1 must be a string or code object&gt;&gt;&gt; c.calc('10/2')&gt;&gt;&gt; c.calc('1/0')Traceback (most recent call last):  File "<pyshell>", line 1, in <module>    c.calc('1/0')  File "<pyshell>", line 5, in calc    return eval(expr)  File "<string>", line 1, in <module>ZeroDivisionError: integer pision or modulo by zero&gt;&gt;&gt; c.muffled=True&gt;&gt;&gt; c.calc('1/0')Division by zero is illegal</module></string></pyshell></module></pyshell></pyshell></module></pyshell>

多种异常类型

立即学习“Python免费学习笔记(深入)”;

try:    x=input('Enter the first number:')    y=input('Enter the seconed number:')    print x/yexcept ZeroDivisionError:    print "The second number can't be zero!"except TypeError:    print "That wasn't a number,was it?"

同时 捕捉多个异常

try:    x=input('Enter the first number:')    y=input('Enter the seconed number:')    print x/yexcept(ZeroDivisionError,TypeError,NameError):    print 'Your numbers were bogus...'

 捕捉对象

try:    x=input('Enter the first number:')    y=input('Enter the seconed number:')    print x/yexcept(ZeroDivisionError,TypeError),e:    print e    Enter the first number:1Enter the seconed number:0integer pision or modulo by zero

 捕捉所有异常

try:    x=input('Enter the first number:')    y=input('Enter the seconed number:')    print x/yexcept:    print 'something wrong happened...'    Enter the first number:something wrong happened...