Python学习记录八---异常

异常
Python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行。

1、raise语句
  >>> raise Exception
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  Exception

  >>> raise Exception("error error error!")
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  Exception: error error error!

2、重要的内建异常类:

  Exception : 所有异常的基类
  AttributeError: 特性引用或赋值失败时引发
  IOError: 试图打开不存在的文件(包括其他情况)时引发
  IndexError: 在使用序列中不存在的索引时引发
  KeyError:在使用映射序列中不存在的键时引发
  NameError:在找不到名字(变量)时引发
  SyntaxError:在代码为错误形式时引发
  TypeError:在内建操作或者函数应用于错误类型的对象时引发
  ValueError:在内建操作或者函数应用于正确类型的对象, 但是该对象使用不合适的值时引发
  ZeroDibivionError:在除法或者模除操作的第二个参数为0时引发

3、自定义异常类
  class SubclassException(Exception):pass

4、捕捉异常
使用 try/except

  >>> try:
  ...      x = input('Enter the first number:')
  ...      y = input('Enter the second number:')
  ...      print x/y
  ...  except ZeroDivisionError:
  ...     print "the second number can't be zero!"
  ...
Enter the first number:2
Enter the second number:0
the second number can't be zero!

5、捕捉对象

  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except (ZeroDivisionError, TypeError), e:
    print e

# 运行输出
Enter the first number:4
Enter the second number:'s'
unsupported operand type(s) for /: 'int' and 'str'

6、全部捕捉
  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except:
    print "Something was wrong"

7、try/except else:
else在没有异常引发的情况下执行

  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except:
    print "Something was wrong"
  else:
    print "this is else"

# 执行后的输出结果
Enter the first number:3
Enter the second number:2
1
this is else

8、finally
可以用在可能异常后进行清理,和try联合使用

  try:
    x = input('Enter the first number:')
    y = input('Enter the second number:')
    print x/y
  except (ZeroDivisionError, TypeError), e:
    print e
  else:
    print "this is else"
  finally:
    print "this is finally"

原文地址:https://www.cnblogs.com/songshu-yilia/p/5239690.html