欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

100_异常

程序员文章站 2022-04-15 11:36:08
...

常见内置异常 - python 官方文档

try- 语句陈述 - 官网文档 - 复合语句


异常处理

一些 示例

可以跟着敲一敲

# try + finally 
# it's work
In [1]: try:
   ...:     print("onepis")
   ...: finally:
   ...:     print("end")
   ...:
onepis
end

# try + except + finally 
# it's work
# 报错的时候  执行 except 里面的语句
# finally  不管是否报错 都执行
In [2]: try:
   ...:     raise ValueError("the value is error ")
   ...: except Exception as e:
   ...:     print("error")
   ...: finally:
   ...:     print("end")
   ...:
error
end

# try + except + finally 
# it's work

In [3]: try:
   ...:     raise ValueError("the value is error ")
   ...: except Exception as e:
   ...:     print(e)
   ...: finally:
   ...:     print("end")
   ...:
the value is error
end
# try + except + else +finally 
# it's work
# 报错的时候 else 里面的语句 不执行

In [4]: try:
   ...:     raise ValueError("the value is error ")
   ...: except Exception as e:
   ...:     print(e)
   ...: else:
   ...:     print("else")
   ...: finally:
   ...:     print("end")
   ...:
the value is error
end
# try + except +else + finally 
# it's work
# 没有报错
# 那么else 里面的语句执行
# 则 except 里面的语句 不执行
In [5]: try:
   ...:     #raise ValueError("the value is error ")
   ...:     print("it's ok")
   ...:
   ...: except Exception as e:
   ...:     print(e)
   ...: else:
   ...:     print("else")
   ...: finally:
   ...:     print("end")
   ...:
it's ok
else
end

# try + else + finally 
# 报错  语法错误
In [6]: try:
   ...:     #raise ValueError("the value is error ")
   ...:     print("it's ok")
   ...: else:
   ...:     print("else")
   ...: finally:
   ...:     print("end")
   ...:
  File "<ipython-input-6-03ea4e78e36a>", line 4
    else:
       ^
SyntaxError: invalid syntax

# try + else 
# 报错  语法错误
In [7]: try:
   ...:     #raise ValueError("the value is error ")
   ...:     print("it's ok")
   ...: else:
   ...:     print("else")
   ...:
   ...:
  File "<ipython-input-7-dbe923b370cd>", line 4
    else:
       ^
SyntaxError: invalid syntax

# try + except 
# it's work
In [8]: try:
   ...:     #raise ValueError("the value is error ")
   ...:     print("it's ok")
   ...: except Exception as e:
   ...:     print(e)
   ...:
   ...:
   ...:
it's ok

In [9]: try:
   ...:     raise ValueError("the value is error ")
   ...:     print("it's ok")
   ...: except Exception as e:
   ...:     print(e)
   ...:
   ...:
   ...:
the value is error





traceback 和 异常处理

import traceback
import sys
try:
    raise KeyError
except:
    print(sys.exc_info()) # 这是一个 元组 所以我们 可以 用下标访问
    traceback.print_tb(sys.exc_info()[2])

100_异常


tips: 对于新手而言 下面代码 可以多练习。
前面两节 写的 os 模块的很多方法 以及 shutil 都有 使用到。
还有以前写过的 嵌套函数。以及很多老的 知识 。 算是一个回顾。
包括 F-string 以及 循环遍历 if 判断。非常有帮助。

import shutil
import os
import time
import traceback
import sys


def move_files(dir_path, target_path):
    """
    :dir_path: 要移动的文件夹
    :target_path: 移动到那个文件夹
    """
    def loop_move():
        # 嵌套函数
        # 循环遍历 文件
        path_li = os.listdir(dir_path)
        if path_li:
            # 如果列表为空 说明没有文件
            for i in path_li:
                if os.path.splitext(i)[1]:
                    shutil.move(os.path.join(dir_path, i), target_path)
            # 移动文件
            print("++ move complete ++")
            time_end = time.time()
            # 结束时间
            print("move the file of time : ", time_end - time_start, " s")
        else:
            print(f"++ {dir_path} is have not file, complete ++")

    time_start = time.time()  # 开始时间
    if os.path.exists(target_path) and os.path.isdir(target_path):
        # 判断目标文件夹是否存在 和 是否 该目标是否是文件夹
        loop_move()
    else:
        print(f"the dir {target_path} is not exists or not a dir")
        print("ready mkdir")
        try:
            os.mkdir(target_path)
            # 创建 文件夹
        except FileExistsError:
            print(sys.exc_info())
            traceback.print_tb(sys.exc_info()[2])
            print("-" * 20 + "\n")
            # ----------------------------
            print(f"the {target_path} is a file ,not a dir,ready remove")
            os.remove(target_path)
            # 移除文件
            print(f"{target_path} is removed")
            os.mkdir(target_path)
        finally:
            loop_move()

测试自定义异常

我们自己写一个异常类

编写异常类

class AgeError(Exception):  # 继承Exception
    def __init__(self, errorInfo):
        Exception.__init__(self)  # 调用父类构造器
        self.errorInfo = errorInfo

    def __str__(self):
        return str(self.errorInfo)+',年龄错误!!!应该在1-150之间!!!'

测试代码

if __name__ == '__main__':  # 如果为True,则模块是作为独立文件运行,可以执行测试代码!
    age = int(input('输入一个年龄:'))
    if age < 1 or age > 150:
        raise AgeError(age)
    else:
        print('正常的年龄:', age)