Python学习笔记之异常处理

一、异常的语法

       python的异常处理语法比较灵活,具有多种,掌握python异常处理的语法的关键是要明白,异常语法中的每个关键字的不同含义。只要我们明白关键字的含义,那么语法也只是一种组合而已。

try:
    f = open('/etc/passwd')
    print(f1)
    f.read()
except OSError as err:
     print("OS error: {0}".format(err))
except  Exception as err:
    print(err)
else:
    print("all success")
finally:
    f.close()
print(f.closed)

输出:

name 'f1' is not defined
True

       在上面一段代码中我们有try except else finally 四个主要的关键字,我们先介绍try,try是告诉python解释器我下面的这些代码可能会出错,我需要异常处理,在我出错的时候将错误抛出。

       except关键字后面接的是改段程序处理的异常类型,如果try语句块抛出的异常的类型是except可可接收的异常类型相同,那么except语句块就可以执行,如果不是就可以判断下一个except语句块。

       else 关键字里面的语句,是所有的except语句块条件不满足,最后被执行的,也就是说我们的try语句块抛出了一个我们写的except语句块未检测到的异常类型。如果else语句之前的except语句块被执行了,那么else语句块就不会被执行。

       finally是指在try语句块抛出异常之后,不论我们的except语句块,else语句块被执行与否,finally语句块都会被执行。

  二、异常的类型

        在python中我们的每一个异常类型都是一个类,我们在官网找到了所有异常类的继承关系树如下:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

      从上面的树形图我们可以看到,BaseException类是所有的异常类的基类。如果骂我们想要捕捉所有的系统自定义的异常类型,我们就可以使用 except BaseException:语句去实现。

      下面一是一些官网的异常示例代码

try:
    file_it = open('/etc/group','r')
    print(file_it.read())
except Exception as e:
    print(e)
#如果没有异常,则执行else 代码
else:
    print('all success')
#不论是否有异常被抛出,finally的代码都会被执行
finally:
    file_it.close()


while True:
    try:
        x = int(input('Please enter a number:'))
    except ValueError:
        print('Oops! That was no valid number')

import  sys
try:
    file_it = open('/tmp/passwd')
    s = file_it.readline()
    i = int(s.strip())
    print(a)
except OSError as err:
    print('OS error:{0}'.format(err))
except ValueError:
    print('Could not convert data to integer.')

except:
    print('Unexpected error:',sys.exc_info()[1])

else:
    print('all ok')
  三、自定义异常类型

        如果我们需要抛出一个自己定义的异常,那么需要们定义一个继承于Exception的类如下面代码

class Error_Test(Exception):
    pass
try:
    print('all is well')
    raise Error_Test('all is well')    #Error_Test 类虽然没有构造函数,但是他的父类有
except Error_Test as err:
    print(err)
finally:
    print('ok')
        raise 关键字用于程序员主动抛出异常,而不是在编译器报错的时候自动抛出异常,因此使用raise的try语句块抛出异常后,该语句块不一定有错误。



猜你喜欢

转载自blog.csdn.net/m0_37717595/article/details/80491940
今日推荐