Python中错误和异常

第1章 概念

  1. 错误
  • 语法错误:代码不符合解释器或编译器的语法
  • 逻辑错误:不完整或不合法的输入或者计算出现问题
  1. 异常:代码执行过程中,出现问题导致程序无法执行
  • 程序遇到逻辑或算法问题
  • 运行过程中计算机错误(内存不够或IO错误)
  1. 区别与联系
  • 错误:代码运行前的语法或逻辑错误
  • 异常:
    异常产生:代码执行中,解释器认为是异常,抛出异常
    异常处理:截获异常并
    处理,否则程序会终止执行

第2章 常见错误和异常

  1. Python标准异常
名称描述
Exception常规错误的基类
BaseException所有异常的基类
NameError未定义变量、初始化对象 (没有属性)
ValueError传入了无效的参数
TypeError无效的操作类型
AttributeError对象没有这个属性
SyntaxErrorPython语法错误
ImportError导入模块/对象失败
IndexError序列中没有此索引(index)
KeyError映射中没有这个键
Warning警告的基类
ZeroDivisionError除零错误
FloatingPointError浮点计算错误
OverflowError数值运算超出最大限制
TabErrorTab 和空格混用
IndentationError缩进错误
FileNotFoundError文件不存在
KeyboardInterrupt用户中断执行(通常是输入^C)
  1. 示例
In [1]: a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-3f786850e387> in <module>()
----> 1 a
NameError: name 'a' is not defined



In [2]: if a
  File "<ipython-input-2-95806c26c887>", line 1
    if a
        ^
SyntaxError: invalid syntax



In [3]: if a:
   ...:     print(a)   
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-7856809510fb> in <module>()
----> 1 if a:
      2     print(a)
      3 

NameError: name 'a' is not defined



In [6]: a = int('a10')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-5b6f560ee82d> in <module>()
----> 1 a = int('a10')

ValueError: invalid literal for int() with base 10: 'a10'



In [5]: 10/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-e574edb36883> in <module>()
----> 1 10/0

ZeroDivisionError: division by zero




In [4]: f = open('test.txt')
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-4-9426bf859622> in <module>()
----> 1 f = open('test.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

第3章 try…except

  1. 语法
try:
      try_suite
except Exception as e:
      except_suite
  • tryexcept:语法关键字,是必须的
  • try_suite:需要处理的代码
  • except_suite:捕获异常后的处理逻辑
  • exception as e:设置异常的类,并将异常保存到变量e
  1. 执行过程
  • try用来捕获try_suite中的异常,并将异常传给except进行处理;
  • except用来处理异常,若捕获的异常与设置的异常一致,使用except_suite进行处理异常;若不一致,则会将捕获的异常传给Python解释器进行处理;
  • 需要处理多个异常时,增加多个except语句即可
  1. 只能捕获代码运行过程中的错误
  • case-1:try…except捕获到一个异常
try:
    a
except BaseException:
    print('Catch an Error')

Catch an Error
  • case-2:try…except没有捕获到异常,而是由Python解释器抛出的异常
try:
    if a
except BaseException:
    print('Catch an Error')

  File "<ipython-input-2-a622bb3e387c>", line 2
    if a
        ^
SyntaxError: invalid syntax
  • 说明:Python代码执行时,由Python解释器将 .py 文件转换成二进制的字节码文件,转换过程中,若代码存在语法错误,则直接会抛出异常,实际上代码还没有开始运行。
  1. 出现的异常与设置的异常不一致时,不会被捕获,但会被Python解释器抛出
  • case-1:try…except捕获到一个异常
try:
    a
except NameError as e:
    print('Catch an Error : ' + str(e))

Catch an Error : name 'a' is not defined
  • case-2:try…except捕获不到异常,Python解释器抛出异常,并停止代码运行
try:
    a
except IOError as e:
    print('Catch an Error : ' + str(e))

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-b89d2b7d14a3> in <module>()
      1 try:
----> 2     a
      3 except IOError as e:
      4     print('Catch an Error : ' + str(e))

NameError: name 'a' is not defined
  1. 示例:猜数字游戏
  • 开始游戏,产生一个1~100之间的随机数
  • 用户输入,游戏根据输入值提示大或者小
  • 用户根据提示,继续输入,直到猜对为止
  • 如果用户输入错误值,程序可以处理异常
  • 使用try…except对输入格式进行保护,确保错误输入时,程序也可以继续进行,增强代码的健壮性
import random
number = random.randint(0, 100) 

while True:
    try:
        guess = int(input('Enter 1~100 :'))    # 输入错误时,提醒用户,而非直接终止程序
    except ValueError as e:
        print('Please enter 1~100 !')
        continue
    if guess > number:
        print('Guess Bigger', guess)
    elif guess < number:
        print('Guess Smaller', guess)
    else:
        print('Guess OK! Game over')
        break
    print('\n')

Enter 1~100 :50
Guess Bigger 50

Enter 1~100 :30
Guess Smaller 30

Enter 1~100 :40d
Please enter 1~100 !

Enter 1~100 :40
Guess Bigger 40

Enter 1~100 :35
Guess Bigger 35

Enter 1~100 :33
Guess OK! Game over
  1. try…except…else语句:如果没有异常时,执行else后的代码
try:
    x
except Exception as e:
    print('Catch an Error : ' + str(e))
else:
    print('No Error')

Catch an Error : name 'x' is not defined


x = 0
try:
    x
except Exception as e:
    print('Catch an Error : ' + str(e))
else:
    print('No Error')

No Error

第4章 try…finally

  1. 语法
try:
      try_suite
finally:
      do_finally
  • tryfinally:语法关键字,是必须的
  • try_suite:需要处理的代码
  • do_finally:清理保护工作(不处理异常)
  1. 执行过程
  • 如果try没有捕获到异常,继续执行do_finally代码;
  • 如果try捕获到异常,仍然继续执行do_finally代码,最后会将捕获的异常传给Python解释器进行处理。
try:
    f = open('test.txt','r')
    number = int(f.read()) 
finally:
    f.close()
    print('File is closed')

File is closed
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-7-174bacfa803b> in <module>()
      1 try:
----> 2     f = open('test.txt','r')
      3     number = int(f.read())
      4 finally:
      5     f.close()

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
  1. 作用
  • 无论try…finally语句是否捕捉到异常,都会执行finally代码;
  • 作用:为异常处理事件提供清理机制,用来关闭文件或释放系统资源。

第5章 try…except…else…finally

  1. try…except…finally
  • 如果try语句没有捕获异常,执行完try代码后,执行finally代码;
  • 如果try语句捕获到异常,首先执行except语句处理错误,再执行finally代码;
  • case-1:try语句捕获到ValueError错误、文件被关闭
try:
    f = open('test.txt')
    number = int(f.read())
except ValueError as e:
    print('Catch an Error : ' + str(e))
except IOError as e:
    print('Catch an Error : ' + str(e))
finally:
    print('File will be closed')
    f.close()

Catch an Error : invalid literal for int() with base 10: 'x123'
File will be closed
  • case-2:try语句捕获到错误,执行finally时,被解释器抛出另一个错误,是因为test—1文件不存在,即f没有并定义。
try:
    f = open('test---1.txt')
    number = int(f.read())
except ValueError as e:
    print('Catch an Error : ' + str(e))
except IOError as e:
    print('Catch an Error : ' + str(e))
finally:
    print('File will be closed')
    f.close() 

Catch an Error : [Errno 2] No such file or directory: 'test1.txt'
File will be closed
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-215addff53c9> in <module>()
      8 finally:
      9     print('File will be closed')
---> 10     f.close()

NameError: name 'f' is not defined
  • case-3:为finally增加try…except异常处理,保护f.close(),避免发生异常
try:
    f = open('test1.txt')
    number = int(f.read())
except ValueError as e:
    print('Catch an Error : ' + str(e))
except IOError as e:
    print('Catch an Error : ' + str(e))
finally:
    try:
        print('File will be closed')
        f.close()
    except NameError as e:
        print('Catch another Error : ' + str(e))

Catch an Error : [Errno 2] No such file or directory: 'test1.txt'
File will be closed
Catch another Error : name 'f' is not defined
  1. try…except…else…finally
  • 如果try语句没有捕获到异常,执行完try代码后,执行else代码,最后执行finally代码
  • 如果try语句捕获到异常,首先执行except语句处理异常,然后再执行finally代码
  • try语句捕获到异常,except语句处理后,没有执行else语句,直接执行了finally语句
try:
    f = open('test.txt')
    number = int(f.read())
except ValueError as e:
    print('Catch an Error : ' + str(e))
except IOError as e:
    print('Catch an Error : ' + str(e))
else:
    print('No Error')
finally:
    print('File will be closed')
    f.close()

Catch an Error : invalid literal for int() with base 10: 'x123'
File will be closed
  • try语句没有捕获到异常,会依次执行else语句和finally语句
try:
    f = open('test.txt')
    number = int(f.read())
except ValueError as e:
    print('Catch an Error : ' + str(e))
except IOError as e:
    print('Catch an Error : ' + str(e))
else:
    print('No Error')
finally:
    print('File will be closed')
    f.close()

No Error
File will be closed

第6章 标准和自定义异常

  1. raise语句
  • 作用:用于主动抛出异常
  • 语法格式:raise [exception [(args)]]
  • exception:异常的类
  • args:描述异常信息的字符串元组
  • 示例
In [1]: raise ValueError ('test is not defined')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-3e52ef4eb7b2> in <module>()
----> 1 raise ValueError ('test name is not defined')

ValueError: test name is not defined
  1. assert语句
  • 作用:是断言语句,用于检查表达式是否为真,如果为假会引发AssertionError错误,并抛出
  • 语法格式:assert expression [, args]
  • expression:表达式内容
  • args:判断条件的字符串描述信息
  • 应用场景:函数或类中的方法,对参数格式有严格的定义时,可以使用assert对传入的参数进行断言判断
  • 示例
In [2]: assert 0, 'test 0 is False'
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-14-0c60f121c0f6> in <module>()
----> 1 assert 0, 'test 0 is False'

AssertionError: test 0 is False
  1. 标准异常
    标准异常:Python内建的异常,程序执行前就已经存在

    《Python中错误和异常》

  2. 自定义异常
  • Python允许自定义异常,用于描述Python中没有涉及的异常情况
  • 自定义异常必须继承Exception类
  • 自定义异常,只能主动触发
  • 简单demo
In [13]: class FileError(IOError):
    ...:     pass
    ...: 

In [14]: raise FileError ('test customize error')
---------------------------------------------------------------------------
FileError                                 Traceback (most recent call last)
<ipython-input-17-b91b6d033ece> in <module>()
----> 1 raise FileError ('test customize error')
  • 示例
# 自定义错误异常
In [15]: class CustomizeError(Exception):    # 自定义的错误类继承于Exception基类
    ...:     def __init__(self, customize_error_info):    # 初始化实例。传入了一个参数:用户自定义错误的信息
    ...:         Exception.__init__(self)    # 初始化了Exception类,
    ...:         self.system_error_info = customize_error_info    # 把用户自定义的错误信息传入
    ...:         
    ...:     def __str__(self):    # 支撑print打印语句的方法
    ...:         return "Customize_error %s" % self.system_error_info    # 打印自定义错误的信息
    ...:     

# 调用自定义的错误异常,并使用try...except进行异常处理
In [16]: try:
    ...:     raise CustomizeError ('test_customeize_error')
    ...: except CustomizeError as e:
    ...:     print("Error_info : %s" % str(e))
    ...:     
Error_info : Customize_error test_customeize_error
    原文作者:惑也
    原文地址: https://www.jianshu.com/p/3af62bc6a7ba
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞