zoukankan      html  css  js  c++  java
  • 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


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

  • 相关阅读:
    给定圆心和半径在圆内随机画点
    mqtt使用二(集成到java代码中)
    mqtt使用一
    vue的细节
    mongodb学习一(使用mongoResposity)
    jadx-gui for Mac
    对xx面APP进行分析
    使用jeb对某圈进行协议分析
    proxifier 安卓模拟器设置全局代理fq
    安卓开启真机调试ro.debuggable 1修改ro属性
  • 原文地址:https://www.cnblogs.com/Renqy/p/12800340.html
Copyright © 2011-2022 走看看