设为首页 加入收藏

TOP

python中异常的介绍
2017-10-09 17:31:49 】 浏览:6720
Tags:python 异常 介绍

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

>>> 1/0

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

异常处理

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

>>> 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"

        
>>> inputnum()
Enter the first number: 10
Enter the first number: 0
The second number can't be zero

raise 触发异常

>>> class Muff:
    muffled=False
    def calc(self,expr):
        try:
            return eva l(expr)
        except ZeroDivisionError:
            if self.muffled:
                print 'Division by zero is illegal'
            else:
                raise

            
>>> c=Muff()
>>> c.calc(10/2)

Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    c.calc(10/2)
  File "<pyshell#31>", line 5, in calc
    return eva l(expr)
TypeError: eva l() arg 1 must be a string or code object
>>> c.calc('10/2')
5
>>> c.calc('1/0')

Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    c.calc('1/0')
  File "<pyshell#31>", line 5, in calc
    return eva l(expr)
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> c.muffled=True
>>> c.calc('1/0')
Division by zero is illegal

多种异常类型

try:
    x=input('Enter the first number:')
    y=input('Enter the seconed number:')
    print x/y
except 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/y
except(ZeroDivisionError,TypeError,NameError):
    print 'Your numbers were bogus...'

 捕捉对象

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

    
Enter the first number:1
Enter the seconed number:0
integer division or modulo by zero

 捕捉所有异常

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

    
Enter the first number:
something wrong happened...

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇python之yield和Generator 下一篇Python2.7 xlwt安装 No module na..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目