[关闭]
@wanghuijiao 2021-06-04T15:58:12.000000Z 字数 5059 阅读 552

[Python3学习笔记] 错误和异常

Python


0. 前言

1. 语法错误和异常

语法错误

异常

2. 异常处理

try/except

  1. import sys
  2. try:
  3. # 先执行这段代码
  4. f = open('myfile.txt')
  5. s = f.readline()
  6. i = int(s.strip())
  7. except (RuntimeError, TypeError, NameError):
  8. pass # 发生异常时执行的代码
  9. except:
  10. # 打印错误信息,用 raise 把错误抛出
  11. print("Unexpected error:", sys.exc_info()[0])
  12. raise

try/except...else

  1. for arg in sys.argv[1:]:
  2. try:
  3. # 先执行这里
  4. f = open(arg, 'r')
  5. except IOError:
  6. # try 有IOError异常,执行这里
  7. print('cannot open', arg)
  8. else:
  9. # try 没异常,执行这里
  10. print(arg, 'has', len(f.readlines()), 'lines')
  11. f.close()

try-finally

  1. try:
  2. runoob()
  3. except AssertionError as error:
  4. print(error)
  5. else:
  6. try:
  7. with open('file.log') as file:
  8. read_data = file.read()
  9. except FileNotFoundError as fnf_error:
  10. print(fnf_error)
  11. finally:
  12. print('这句话,无论异常是否发生都会执行。')

3. 抛出异常

  1. x = 10
  2. if x > 5:
  3. raise Exception('x 不能大于 5。x 的值为: {}'.format(x))

4. 用户自定义异常(拓展学习)

  1. >>> class MyError(Exception):
  2. def __init__(self, value):
  3. self.value = value
  4. def __str__(self):
  5. return repr(self.value)
  6. >>> try:
  7. raise MyError(2*2)
  8. except MyError as e:
  9. print('My exception occurred, value:', e.value)
  10. My exception occurred, value: 4
  11. >>> raise MyError('oops!')
  12. Traceback (most recent call last):
  13. File "<stdin>", line 1, in ?
  14. __main__.MyError: 'oops!'
  1. class Error(Exception):
  2. """Base class for exceptions in this module."""
  3. pass
  4. class InputError(Error):
  5. """Exception raised for errors in the input.
  6. Attributes:
  7. expression -- input expression in which the error occurred
  8. message -- explanation of the error
  9. """
  10. def __init__(self, expression, message):
  11. self.expression = expression
  12. self.message = message
  13. class TransitionError(Error):
  14. """Raised when an operation attempts a state transition that's not
  15. allowed.
  16. Attributes:
  17. previous -- state at beginning of transition
  18. next -- attempted new state
  19. message -- explanation of why the specific transition is not allowed
  20. """
  21. def __init__(self, previous, next, message):
  22. self.previous = previous
  23. self.next = next
  24. self.message = message

5. 定义清理行为(拓展学习)

  1. >>> def divide(x, y):
  2. try:
  3. result = x / y
  4. except ZeroDivisionError:
  5. print("division by zero!")
  6. else:
  7. print("result is", result)
  8. finally:
  9. print("executing finally clause")
  10. >>> divide(2, 1)
  11. result is 2.0
  12. executing finally clause
  13. >>> divide(2, 0)
  14. division by zero!
  15. executing finally clause
  16. >>> divide("2", "1")
  17. executing finally clause
  18. Traceback (most recent call last):
  19. File "<stdin>", line 1, in ?
  20. File "<stdin>", line 3, in divide
  21. TypeError: unsupported operand type(s) for /: 'str' and 'str'

6. 预定义的清理行为(拓展学习)

  1. for line in open("myfile.txt"):
  2. print(line, end="")
  1. with open("myfile.txt") as f:
  2. for line in f:
  3. print(line, end="")

7. Debug

  1. def foo(s):
  2. n = int(s)
  3. # assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。
  4. assert n != 0, 'n is zero!'
  5. return 10 / n
  6. def main():
  7. foo('0')
  8. # 断言失败则会报错:
  9. $ python err.py
  10. Traceback (most recent call last):
  11. ...
  12. AssertionError: n is zero!
  13. # 用 -O 关闭,关闭后,可以把所有的assert语句当成pass来看。
  14. $ python -O err.py
  15. Traceback (most recent call last):
  16. ...
  17. ZeroDivisionError: division by zero
  1. import logging
  2. logging.basicConfig(level=logging.INFO)
  3. s = '0'
  4. n = int(s)
  5. logging.info('n = %d' % n)
  6. print(10 / n)
  1. # err.py
  2. import pdb
  3. s = '0'
  4. n = int(s)
  5. pdb.set_trace() # 运行到这里会自动暂停
  6. print(10 / n)
  7. # 调试
  8. $ python err.py
  9. > /Users/michael/Github/learn-python3/samples/debug/err.py(7)<module>()
  10. -> print(10 / n)
  11. (Pdb) p n
  12. 0
  13. (Pdb) c
  14. Traceback (most recent call last):
  15. File "err.py", line 7, in <module>
  16. print(10 / n)
  17. ZeroDivisionError: division by zero
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注