1.认识异常

程序执行时会抛出异常

  1. open('abc','r')
  2. # 结果
  3. Traceback (most recent call last):
  4. File "F:/Pycharm/pyselenium/ExceptionObj.py", line 1, in <module>
  5. open('abc','r')
  6. FileNotFoundError: [Errno 2] No such file or directory: 'abc'

如果知道报错类型为FileNotFoundError,我们可捕捉异常

  1. try:
  2. open('abc', 'r')
  3. except FileNotFoundError:
  4. print('异常了')
  5. # 结果
  6. 异常了

如果程序报错不是FileNotFoundError类型,仍会抛出异常

  1. try:
  2. print(a)
  3. except FileNotFoundError:
  4. print('异常了')
  5. # 结果
  6. Traceback (most recent call last):
  7. File "F:/Pycharm/pyselenium/ExceptionObj.py", line 9, in <module>
  8. print(a)
  9. NameError: name 'a' is not defined

若不知异常类型,可捕捉基类BaseException

  1. try:
  2. open('abc', 'r')
  3. print(a)
  4. except BaseException as msg:
  5. print(msg)
  6. # 结果
  7. [Errno 2] No such file or directory: 'abc'

2.raise抛出异常

可使用raise自定义抛出的异常

  1. def say_hello(name=None):
  2. if name is None:
  3. raise NameError('"name" cannot be empty')
  4. else:
  5. print('hello %s'%name)
  6. say_hello()
  7. # 结果
  8. Traceback (most recent call last):
  9. File "F:/Pycharm/pyselenium/ExceptionObj.py", line 31, in <module>
  10. say_hello()
  11. File "F:/Pycharm/pyselenium/ExceptionObj.py", line 26, in say_hello
  12. raise NameError('"name" cannot be empty')
  13. NameError: "name" cannot be empty

捕捉NameError

  1. def say_hello(name=None):
  2. if name is None:
  3. raise NameError('"name" cannot be empty')
  4. else:
  5. print('hello %s'%name)
  6. try:
  7. say_hello()
  8. except NameError as msg:
  9. print(msg)
  10. # 结果
  11. "name" cannot be empty

注:raise只能使用python提供的异常类。如果想用raise使用自定义异常类,则自定义异常类需要继承Exception类。