捕捉对象

在except子句中访问中访问异常对象本身:

try:
    x = input('Enter the first number: ')
    y = input('Enter the second number: ')
    print x/y
except (ZeroDivisionError, TypeError), e:
    print e

在Python 3.0中except子句需写作except (ZeroDivisionError, TypeError) as e

except子句中忽略所有异常类可以捕捉所有异常:

try:
    x = input('Enter the first number: ')
    y = input('Enter the second number: ')
    print x/y
except:
    print 'Something wrong happened...'

可添加else子句在程序正常运行后执行:

while Truetry:
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
    except:
        print 'Invalid input. Please try again.'
    else:
        break

finally子句可用于在可能的异常后进行清理;无论是否发生异常,finally子句都会被执行;

results matching ""

    No results matching ""