1. try:
  2. s = input('please enter two numbers separated by comma: ')
  3. num1 = int(s.split(',')[0].strip())
  4. num2 = int(s.split(',')[1].strip())
  5. ...
  6. except (ValueError, IndexError) as err:
  7. print('Error: {}'.format(err))
  8. print('continue')
  9. ...

当try block中发生了符合except后面的exception类型匹配时 会执行 except block里的代码
也等同于以下写法

  1. try:
  2. s = input('please enter two numbers separated by comma: ')
  3. num1 = int(s.split(',')[0].strip())
  4. num2 = int(s.split(',')[1].strip())
  5. ...
  6. except ValueError as err:
  7. print('Value Error: {}'.format(err))
  8. except IndexError as err:
  9. print('Index Error: {}'.format(err))
  10. print('continue')
  11. ...

以下为最通常的写法(覆盖率最高)

  1. try:
  2. s = input('please enter two numbers separated by comma: ')
  3. num1 = int(s.split(',')[0].strip())
  4. num2 = int(s.split(',')[1].strip())
  5. ...
  6. except ValueError as err:
  7. print("Value Error :{}".format(err:))
  8. except IndexError as err:
  9. print("Index Error:{}".format(err))
  10. except Exception as err:
  11. print('other error:{}'.format(err))
  12. print('continue')

也可以在 except 后面省略异常类型,这表示与任意异常相匹配(包括系统异常等):

  1. try:
  2. s = input('please enter two numbers separated by comma: ')
  3. num1 = int(s.split(',')[0].strip())
  4. num2 = int(s.split(',')[1].strip())
  5. ...
  6. except ValueError as err:
  7. print('Value Error: {}'.format(err))
  8. except IndexError as err:
  9. print('Index Error: {}'.format(err))
  10. except:
  11. print('Other error')
  12. print('continue')
  13. ...

当程序中存在多个 except block 时,最多只有一个 except block 会被执行。换句话说,如果多个 except 声明的异常类型都与实际相匹配,那么只有最前面的 except block 会被执行,其他则被忽略。

文件 的读取案例

  1. import sys
  2. try:
  3. f = open('file.txt', 'r')
  4. .... # some data processing
  5. except OSError as err:
  6. print('OS error: {}'.format(err))
  7. except:
  8. print('Unexpected error:', sys.exc_info()[0])
  9. finally:
  10. f.close()

自定义异常类

实际工作中,如果内置的异常类型无法满足我们的需求,或者为了让异常更加详细、可读,想增加一些异常类型的其他功能,我们可以自定义所需异常类型。

  1. class MyInputError(Exception):
  2. """Exception raised when there're errors in input"""
  3. def __init__(self, value): # 自定义异常类型的初始化
  4. self.value = value
  5. def __str__(self): # 自定义异常类型的string表达形式
  6. return ("{} is invalid input".format(repr(self.value)))
  7. try:
  8. raise MyInputError(1) # 抛出MyInputError这个异常
  9. except MyInputError as err:
  10. print('error: {}'.format(err))