zoukankan      html  css  js  c++  java
  • Python之异常处理

    当一个程序运行时报错,可以通过Python异常处理机制忽略错误或者以友好的方式提示错误

    vim day8-2.py

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    try:
        input = raw_input()
        data = int(input)
        print data
    except Exception,e:
        print '请输入数字'
    

    错误有很多种可以定义对于某一种异常进行处理

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    try:
        dic = {'k1','v1'}
        dic['ddd']
    except IndexError,e: #如果出现IndexError错误执行下面的
        print 'errot',e
    except KeyError,e:   #如果出现KeyError错误执行下面的    
        print e
    except TypeError,e:   #如果出现KeyError错误执行下面的   
        print e
                         #如果以上错误均为出现则报错 
    

    PS:可以在最后加 except Exception,e:处理所有无法预测到的错误

    以上的捕获异常代码异常,还有一种异常是主动触发异常,如果是自己想让代码出现异常

    创建一个模块helper.py提供了很多公共的组件

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    
    def f1():
        return False
    
    def f2():
        pass
    
    def f3():
        pass
    

    vim day8-4.py

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    import helper
    if __name__ == '__main__':
        try:
            n = "1"
            n = int(n)
            ret = helper.f1()
            if ret:
                print 'chenggong'
            else:
    #            print 'shibai'
                raise Exception('error')
        except Exception,e:
            print "出现错误"
            print e
            #记录日志,e
    

    在里面调用另外的模块如果另外的模块执行错误则主动触发一个异常(这里通过f1返回False强行触发错误)并且封装到e里面,然后打印出来

    自定义异常

    vim day8-5.py

    class AlexError(Exception):
        def __str__(self):
            return 'alex error'
    
    try:
        raise AlexError()
    except Exception,e:
        print e
    

    以上自定义异常输出一直不变修改代码动态更新异常

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    class AlexError(Exception):     #定义类继承Exception
        def __init__(self,msg=None):
            self.message = msg
        def __str__(self):
            if self.message:
                return self.message
            else:
                return 'alex error'
    
    try:
        raise AlexError('dasdkj')
    except Exception,e:
        print e

    异常及为传递的字符串

    不传递参数返回错误为alex error

     异常处理之断言

    满足条件则执行

    assert 1==1

    assert 1==2

  • 相关阅读:
    多表查询 left join
    对JS关于对象创建的几种方式的整理
    常见正则表达式
    spring
    富文本编辑器
    Struts2快速入门
    一个MySql Sql 优化技巧分享
    maven
    day3
    Spring MVC
  • 原文地址:https://www.cnblogs.com/minseo/p/6909603.html
Copyright © 2011-2022 走看看