zoukankan      html  css  js  c++  java
  • 05-python中的异常

    python的所有的异常都继承自基类: Exception

    处理方式和java类似: 

    path = raw_input('input the path')
    array = path.split('/')
    try :
        module = __import__('model.' + array[0])
        model = getattr(module, array[0])
        func = getattr(model, array[1])
        func()
    except (ImportError, AttributeError, NameError), e:
        print(e)
    
    finally:
        print('finally to do')

    多个异常的捕捉, 可以使用连续的exept或者使用括号进行捕捉

    import sys
    
    try:
        f = open('myfile.txt')
        s = f.readline()
        i = int(s.strip())
    except OSError as err:
        print("OS error: {0}".format(err))
    except ValueError:
        print("Could not convert data to an integer.")
    except:
        print("Unexpected error:", sys.exc_info()[0])
        raise
    else :
      print ('else method')

    python的异常还有一个else子句, 没有任何异常的时候去执行

    自定义异常: 

    和其他语言一样, python也可以进行自定义异常, 并且抛出; 

    class MyException(Exception):
    
        def __init__(self, name):
            self.name = name
    
        # 重写string方法
        def __str__(self, *args, **kwargs):
            return self.name

    在其他地方进行抛出的方法: 

    try:
        print('start...')
        raise MyException('raise exception')
    except MyException as err:
        print(err)
    finally:
        print('finally')

    使用raise关键字进行抛出

  • 相关阅读:
    LeetCode 023 Merge k Sorted Lists
    LeetCode 022 Generate Parentheses
    LeetCode 020 Valid Parentheses
    LeetCode 019 Remove Nth Node From End of List
    LeetCode 018 4Sum
    LeetCode 017 Letter Combinations of a Phone Number
    Linux常用命令详解(3)
    Linux常用命令详解(2)
    Linux常用命令详解(1)
    部署cobbler服务器
  • 原文地址:https://www.cnblogs.com/wenbronk/p/7141728.html
Copyright © 2011-2022 走看看