Python 之异常处理

作者: ropon 分类: Python 发布时间: 2018-10-19 12:40
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/10/17 14:24
# @Author  : Ropon
# @File    : 20_01.py

# 异常是什么,比如:
# IndexError [][1]
# KeyError {}['key']
# EOFError pickle.load()
# FileNotFoundError open('aaaa')
# ModuleNotFoundError import aaaaaaadfdsdf
# ValueError int('dsfsdfsdf')

# 语法错误,编写代码时就应该规避掉
# SyntaxError
# NameError name

# 什么时候容易出现异常,当您输入的内容不确定,比如:
#     有用户参与输入
#     有外界数据接入,比如从文件中读,从网络中获取

# 多行报错的原因是:一般在嵌套调用过程中,内部代码出现异常,外部所有调用的地方都成为报错追溯信息的一部分

# def func1():
#     name
#
# def func2():
#     func1()
#
# def func3():
#     func2()
#
# def main():
#     func3()
#
# main()

# 遇到多行报错,如何分析
# 从下往上分析,逐个检查出错行,分析您自己写的代码
# 如果找不到问题,就将最后一行的错误类型及详细提示复制到百度搜索

# lst = ['login', 'register']
# for num, i in enumerate(lst , 1):
#     print(num, i)
#
# try:
#     num = int(input("num >>"))
#     print(lst[num - 1])
# except ValueError:
#     print("请输入一个数字")

# lst = ['login', 'register']
# for num, i in enumerate(lst , 1):
#     print(num, i)
# try:
#     num = int(input("num >>"))
#     print(lst[num - 1])
# except ValueError:
#     # 从上往下错误代码,匹配到一个报错类型分支就执行这个分支中的代码,然后退出分支
#     print("请输入一个数字")
# except IndexError:
#     # 如果找不到匹配的分支,就一直往下查找,最后依然没有找到匹配就报错
#     print("只能输入1或2")

#合并多分支
# lst = ['login', 'register']
# for num, i in enumerate(lst , 1):
#     print(num, i)
# try:
#     num = int(input("num >>"))
#     print(lst[num - 1])
# except (ValueError, IndexError):
#     print("输入不合法")

#万能异常
# def buy():
#     print("buy")
#     name
#
# def back():
#     print("back")
#     [][1]
#
# def show():
#     print("show")
#     1/0
#
# def main():
#     lst = [('购物', buy), ('退货', back), ('查看订单', show)]
#     while 1:
#         for num, i in enumerate(lst, 1):
#             print(num, i[0])
#         num = int(input("num >>>"))
#         try:
#             print(lst[num - 1])
#             func = lst[num - 1][1]
#             func()
#         except (ValueError, IndexError):
#             print('您输入的内容不合法')
#         except Exception:
#             print("用户选择%s操作之后发生未知错误" % lst[num - 1][0])
#
# if __name__ == '__main__':
#     main()

# as语法  能够将具体错误信息打印出来
# def buy():
#     print("buy")
#     name
#
# def back():
#     print("back")
#     [][1]
#
# def show():
#     print("show")
#     1/0
#
# def main():
#     lst = [('购物', buy), ('退货', back), ('查看订单', show)]
#     while 1:
#         for num, i in enumerate(lst, 1):
#             print(num, i[0])
#         num = int(input("num >>>"))
#         print(lst[num - 1])
#         try:
#             func = lst[num - 1][1]
#             func()
#         except Exception as e:
#             print(e)
#             print("用户选择%s操作之后发生未知错误" % lst[num - 1][0])
#
# if __name__ == '__main__':
#     main()
# 万能异常相当于except Exception
# try:
#     name
#     [][1]
#     int('aaa')
# # except:
# except Exception:
#     print("123")

# 多分支 万能异常,万能异常应该永远放到异常处理最下面

# def buy():
#     print("buy")
#     name
#
# def back():
#     print("back")
#     [][1]
#
# def show():
#     print("show")
#     1/0
#
# def main():
#     lst = [('购物', buy), ('退货', back), ('查看订单', show)]
#     while 1:
#         for num, i in enumerate(lst, 1):
#             print(num, i[0])
#         num = int(input("num >>>"))
#         try:
#             print(lst[num - 1])
#             func = lst[num - 1][1]
#             func()
#         except (ValueError, IndexError):
#             print('您输入的内容不合法')
#         except Exception:
#             print("用户选择%s操作之后发生未知错误" % lst[num - 1][0])
#
# if __name__ == '__main__':
#     main()

# 总结
# try:
#     pass
# except (ValueError,IndexError):
#     print("针对性处理异常")
# except Exception as e:
#     print("通用办法处理异常")

# else分支
# try:
#     print("test")
#     # name
#     # [][1]
#     # 1/0
# except NameError:
#     print("NameError")
# except IndexError:
#     print("IndexError")
# except Exception as e:
#     print(e)
# else:
#     print("else")

# finally分支
# try:
#     print("test")
#     # name
#     # [][1]
#     # 1/0
# except NameError:
#     print("NameError")
# except IndexError:
#     print("IndexError")
# except Exception as e:
#     print(e)
# else:
#     print("else")
# finally: # 无论如何都会被执行
#     print("finally")

# def func():
#     f = open('test.txt', 'r')
#     try:
#         while 1:
#             for line in f:
#                 if line.startswith('a'):
#                     return line
#     except:
#         print("异常处理")
#     finally: # 即使return也会先执行fianlly中的代码
#         f.close()
#
# print(func())

# try:
#     f = open('test.txt', 'r')
#     f.read()
#     name
# finally: #即使程序报错,在程序结束之前也会执行此分支代码
#     f.close()
#     print("已关闭打开的文件")

# finally 通常用来回收一些系统的资源,比如数据连接,打开的文件,网络连接等
# 异常处理常用:
# try ... except
# try ... except ... else
# try ... finally
# try ... except ... finally
# try ... except ... else ... finally

# 主动抛出异常,主要是给其他开发者看的
# raise ValueError("你写的不正确")

# python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。
# 可以理解assert断言语句为raise-if-not,用来测试表示式,其返回值为假,就会触发异常。
# assert 2==1 False
# assert 1==1 True
# print("test")

# if 1 == int(input()):
#     print("test")
# else:
#     raise AssertionError

# 自定义异常

# 最外层的异常处理应该在所有开发完成后才考虑,一般最后将错误写到文件中。
# def main():
#     name
# try:
#     main()
# except Exception as e:
#     with open('error.log', 'a', encoding='utf-8') as f:
#         f.write(str(e))

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!