Python3学习七之异常处理

来源:互联网 发布:汽车驾驶模拟器软件 编辑:程序博客网 时间:2024/06/03 21:38

Python3学习七之异常处理大笑类似于java的try...catch

基本语法

try:   block1except Error:   block2

  1. except可以处理多个异常,将多个异常放入()内并使用,隔开就行了
  2. except中可以打印错误信息,将Error用关键字as命名err即可调用print
  3. try中还可以加入另一个子句finally,无论try是否发生异常finally的语句都会执行
  4. try...except后面可以跟else语句,其中当try中没有任何报错的情况下程序才会执行else的语句
举个例子:
def divide(x, y):        try:            result = x / y        except ZeroDivisionError:            print("division by zero!")        else:            print("result is", result)        finally:            print("executing finally clause")


自定义异常
可以通过创建一个新的exception类来拥有自己的异常。异常应该继承自 Exception 类,当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:

class Error(Exception):    """Base class for exceptions in this module."""    passclass 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 = messageclass 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
预定义的清理行为

用关键字with,可以保证文件对象等在使用完之后一定会正确执行清理方法

with open("test.txt") as f:    for line in f:        print(line, end="")
无论处理过程是否顺利,文件都会关闭


1 0
原创粉丝点击