• 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
    
  • 相关阅读:
    centos7 rc.local 开机不执行
    springboot与tomcat中GZip压缩
    使用Nginx对Websocket进行反向代理
    spring-data-redis 关于订阅客户端不断创建新线程的问题
    使用apache.tika判断文件类型
    简单理解TCP通信的三次握手
    logback异步输出日志(生产者消费者模型),并非批量写入日志。
    将文本(lrc,txt)文件转换成UTF-8格式
    docker入门(三)
    Spring session(redis存储方式)监听导致创建大量redisMessageListenerContailner-X线程
  • 原文地址:https://www.cnblogs.com/sslblog/p/6930420.html
Copyright © 2020-2023  润新知