python异常处理机制(try:except)

语法结构:

try:
    #'尝试执行的语句'
except 异常名称 as msg:
    print('提示外界的语句')
finally:
    #'不管有没有异常产生,都会执行的语句'
    #文件关闭、释放锁、数据库链接返还给连接池等

下面是一个打开文件操作的异常捕获机制。

finally里执行的语句如果可能有异常产出,可以进行if判断或者在嵌套一个try:except都可以。

代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def openfile(filename):
    try :
        f = open(filename)
    except FileNotFoundError as msg:
        print("您指定的文件不存在")
    finally :
        #文件关闭、释放锁、数据库链接返还给连接池
        try :
            f.close()
            print("文件已关闭")
        except UnboundLocalError as msg:
            pass


filename = input("请输入您要操作的文件:")
# if filename == "hello":
#     raise FileNotFoundError("名字错误")
# #raise 抛出异常
openfile(filename)

里面有个raise注释掉了。

这里解释一下,raise是主动抛出异常。上面可能不太好理解。我们看下面一个例子:

#!/usr/bin/python
# -*- coding: utf-8 -*-

sweet = int(input("请输入糖果个数:"))
children = int(input("请输入来了几个小朋友:"))
if sweet<children:
    raise ValueError("糖果太少了,不够分...")

n = sweet//children
print("每位小朋友可以分到",n,"个糖果")

小朋友分糖果:

1、糖果的个数大于小朋友的个数,那么糖果分起来没有问题,每人至少一个糖果。

2、糖果的个数小于小朋友的个数,如果没有raise的话,分起来每人是0个,或者还需要在后面加判断,看这个n是否>=1。

对于2情况出现问题,如果我们不想在当前程序中处理这个异常,则可以使用raise提前给它抛出来。

注意:raise 异常名,这个名字必须是可识别的异常类型,不能够随意写的。

python 3 异常类型结构如下:

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


读书和健身总有一个在路上

posted @ 2020-04-29 10:11  Renqy  阅读(579)  评论(0编辑  收藏  举报