• python快速学习6


    语法错误和异常

    异常处理

    try语句

    try和except组合使用

    >>> try:
    ...     f = open('E:\test_for_filefun1.txt','rb+') 
    ...     s = f.readline()
    ... except IOError as e:
    ...     print "I/O error({0}):{1}".format(e.errno, e.strerror)
    ... except ValueError:
    ...     print "could not convert data to int"
    ... except :
    ...     print "Unexpected error:", sys.exc_info()[0]
    ...     
    I/O error(2):No such file or directory
    

    else
    try except 和else的组合使用
    else必须放在所有的except之后.当try语句中没有抛出异常时,就会执行else中的代码

    >>> try:
    ...     f = open('E:\test_for_filefun.txt','rb+') 
    ... except IOError as e:
    ...     print "I/O error({0}):{1}".format(e.errno, e.strerror)
    ... except :
    ...     print "Unexpected error:", sys.exc_info()[0]
    ... else:
    ...     f.write(str(ip))
    ...     f.close()
    ...     
    

    raise引发的异常

    raise为引发一个异常
    常用 raise ValueError

    >>> raise NameError('song')
    Traceback (most recent call last):
      File "D:PyCharm Community Edition 2017.1.3helperspydev\_pydevd_bundlepydevd_exec.py", line 3, in Exec
        exec exp in global_vars, local_vars
      File "<input>", line 1, in <module>
    NameError: song
    

    自定义的异常Exception

    可以通过派生Exception类来创建自定义的异常类型

    >>> class MyError(Exception):
    ...     def __init__(self,value):
    ...         self.value = value
    ...     def __str__(self):
    ...         return repr(self.value)
    ...     
    >>> raise MyError('good')
    Traceback (most recent call last):
      File "D:PyCharm Community Edition 2017.1.3helperspydev\_pydevd_bundlepydevd_exec.py", line 3, in Exec
        exec exp in global_vars, local_vars
      File "<input>", line 1, in <module>
    MyError: 'good'
    

    标准的做法

    • 为Exception定义一个异常基类
    • 然后根据这个基类Error派生出对应的子类
    class Error(Exception):
        """Base class for exceptions in this module."""
        pass
    
    class InputError(Error):
        """Exception raised for errors in the input.
    
        Attributes:
            expression -- input expression in which the error occurred
            message -- explanation of the error
        """
    
        def __init__(self, expression, message):
            self.expression = expression
            self.message = message
    
    class TransitionError(Error):
        """Raised when an operation attempts a state transition that's not
        allowed.
    
        Attributes:
            previous -- state at beginning of transition
            next -- attempted new state
            message -- explanation of why the specific transition is not allowed
        """
    
        def __init__(self, previous, next, message):
            self.previous = previous
            self.next = next
            self.message = message
    

    finally语句

    无论什么情况下都会执行
    常用语释放外部的资源(文件,网络连接...)

    >>> def test_for_error(x, y):
    ...     try:
    ...         result = x/y
    ...     except ZeroDivisionError:
    ...         print 'y is 0 ,division zero error'
    ...     else:
    ...         print result
    ...     finally:
    ...         print 'excute the finally clause'
    ...         
    >>> test_for_error(3,3)
    1
    excute the finally clause
    >>> test_for_error(3,0)
    y is 0 ,division zero error
    excute the finally clause
    
  • 相关阅读:
    解决ASP.NET MVC3与FusionCharts乱码问题
    php中sprintf与printf函数用法区别
    常用的CSS缩写语法一些方法小结
    linux中利用iptables+geoip过滤指定IP
    php中magic_quotes_gpc对unserialize的影响
    mysql中权限参数说明
    jquery实现点击页面空白隐藏指定菜单
    asp.net中导出excel数据的方法汇总
    SQL取某个字段最大(小)数值及其相应行的其他字段值的句语
    Dos下查询关闭端口的命令例子
  • 原文地址:https://www.cnblogs.com/sslblog/p/6930420.html
Copyright © 2020-2023  润新知