Python—— 21.try

1.try-except-else-finally

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必须放在所有的except子句之后,在try子句没有发生任何异常的时候执行。

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

2.抛出异常

raise 语句抛出一个指定的异常。抛出的异常必须是一个异常的实例或者是异常的类,也就是 Exception 的子类。

>>>raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere 
In [56]: sys.exc_info?                                                                                                                 
Docstring:
exc_info() -> (type, value, traceback)

Return information about the most recent exception caught by an except
clause in the current stack frame or in an older stack frame.
Type:      builtin_function_or_method

3.自定义异常

异常类继承自 Exception 类,可以直接继承,或者间接继承。

>>>class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
   
>>> try:
        raise MyError(2*2)
    except MyError as e:
        print('My exception occurred, value:', e.value)
   
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

类 Exception 默认的 init() 被覆盖。当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子。

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

————Blueicex 2020/2/22 22:38 [email protected]

发布了118 篇原创文章 · 获赞 1 · 访问量 4494

猜你喜欢

转载自blog.csdn.net/blueicex2017/article/details/104450954