美文网首页
python异常处理

python异常处理

作者: 知识学者 | 来源:发表于2018-06-01 21:55 被阅读65次

    程序的错误通常分为,语法错误,运行错误和逻辑错误

    一个最常见的错误

    >>> print(a)
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        print(a)
    NameError: name 'a' is not defined
    

    python的异常

    异常类名 说明
    Exception 所有异常的基类
    AttributeError 访问未知对象的属性
    IOError io异常
    IndexError 不存在的索引
    NameError 不存在的变量名

    异常处理的语句

    try:
        语句块
    except:
        异常处理的语句
    

    python中,异常处理是通过try--except语句实现的,try检测语句块中的错误,except语句是捕获异常,并进行处理。如果不希望程序在异常发生而结束,只需在try捕获。

    执行try语句块,如果正常则结束到try--ecxept语句下一条语句,否则执行exception的异常处理语句

    def calcu():
        a,b=eval(input())
        try:
            end=a/b
            print('end=',end)
        except:
            print('error')
        
    

    结果

    >>> calcu()
    1,2
    end= 0.5
    >>> calcu()
    1,0
    error
    

    分类异常处理

    
    def main():
        a,b=eval(input())
        try:
            s=a/b
            print('s=',s)
        except TypeError :
            print('数据类型异常,')
        except ZeroDivisionError as e:
            print('除数为0,',e)
        except:
            print(' 发生exception')
        else:
            print('正常结束')
    
    

    结果是

    >>> main()
    1,'1'
    数据类型异常,
    >>> main()
    1,0
    除数为0, division by zero
    >>> main()
    2,3
    s= 0.6666666666666666
    正常结束
    

    try--finally语句。
    finally语句是指无论是否发生,都执行相应的语句块。

    import os
    def main():
        try:
            f1=open('C:\\HelloWorld.txt','r+')
            f2=open('c:\\test.txt','w+')
            f3=f1.read()
            f1.seek(0)
            print(f3)
            print('----------')
            for c in f1:
                f2.write(c)
        except:
            print(' has except')
        finally:
            print('close file')
            f2.flush()
            #f2.seek(0)
            f6=f2.read()
            print(f6)
            f1.close()
            f2.close()
        
    
    

    结果

    public class HelloWorld{
     
    public  static void main(String []args)
    {
      System.out.println("helllo world");
    }
    
    
    }
    ----------
    close file
    

    异常还可以自定义,通过继承Exception,还可以主动引起异常,还可以设置断言

    通过raise触发异常,但是需要处理异常
    raise [Exception [, args [, traceback]]]

    
    import math
    def getException(lev):
        if lev<0:
            raise Exception('invalid lev')
        
    
    def getSqrt(num):
        try:
            getException(num)
            i=0
            y=math.sqrt(num)
            print('{0}*{1}={2}'.format(y,y,num))
        except Exception as e:
            print('error',e)
    
    

    自定义异常,需要面向对象的知识点.

    
    class  FileException(Exception):
        def __init__(self,arg):
            self.arg=arg
        def __str__(self):
            return repr(self.arg)
        
    try:
        raise FileException('\home')
    except FileException  as e:
        print('error ',e.arg)
    
    

    结果是:

    
    IPython 6.2.1 -- An enhanced Interactive Python.
    error  \home
    

    时间好快啊,快点结束python,我准备玩Java了,这才是我主要的方向.

    参考文献
    Python3 错误和异常

    相关文章

      网友评论

          本文标题:python异常处理

          本文链接:https://www.haomeiwen.com/subject/guutsftx.html