python 异常 try-except句型

来源:互联网 发布:400块一家收淘宝店铺 编辑:程序博客网 时间:2024/06/06 08:59

1.句型

try:     表达式 1(如果表达式,可以成功执行,则执行,跳到 finally 语句)except ExpectErrorType, Argument:   (表达式1 没有做成功,且正好是 ExpectErrorType 的错误情况,则执行)     表达式2 (如何处理这种异常情况)else:  (try succ && 上面 except 语句任一满足 )之外的情况处理方法  .....finally:    .... 无论什么情况都会的处理

2.except 子句解释

except ExceptErrorType , Argument:
ExceptErrorType: 期待的错误类型
Argument 是异常类的实例, 包含来自异常代码的诊断信息。如果你捕获了一个异常,你就可以通过这个异常类的实例来获取更多的关于这个异常的信息。

>>> try:  ...     1/0  ... except ZeroDivisionError,reason:  ...     pass  ...   >>> type(reason)  <type 'exceptions.ZeroDivisionError'>  >>> print reason  integer division or modulo by zero  >>> reason  ZeroDivisionError('integer division or modulo by zero',)  >>> reason.__class__  <type 'exceptions.ZeroDivisionError'>  >>> reason.__class__.__doc__  'Second argument to a division or modulo operation was zero.'  >>> reason.__class__.__name__  'ZeroDivisionError' 

3.多个异常:

1)写多个except 子句

2)一个except 子句传多个参数

e.gtry:      floatnum = float(raw_input("Please input a float:"))      intnum = int(floatnum)      print 100/intnum  except ZeroDivisionError:      print "Error:you must input a float num which is large or equal then 1!"  except ValueError:      print "Error:you must input a float num!"  [root@]# python test.py   Please input a float:fjia  Error:you must input a float num!  [root@]# python test.py   Please input a float:0.9999  Error:you must input a float num which is large or equal then 1!  [root@]# python test.py   Please input a float:25.091  4  

4.异常情况 ExceptErrorType

BaseException+-- SystemExit+-- KeyboardInterrupt+-- GeneratorExit+-- Exception+-- StopIteration+-- StandardError|    +-- BufferError|    +-- ArithmeticError|    |    +-- FloatingPointError|    |    +-- OverflowError|    |    +-- ZeroDivisionError 除数为0|    +-- AssertionError|    +-- AttributeError  尝试访问未知的对象属性|    +-- EnvironmentError|    |    +-- IOError  输入输出错误(比如你要读的文件不存在)|    |    +-- OSError|    |         +-- WindowsError (Windows)|    |         +-- VMSError (VMS)|    +-- EOFError|    +-- ImportError|    +-- LookupError|    |    +-- IndexError 索引超出序列范围|    |    +-- KeyError 请求一个不存在的字典关键字|    +-- MemoryError|    +-- NameError  尝试访问一个没有申明的变量|    |    +-- UnboundLocalError|    +-- ReferenceError|    +-- RuntimeError|    |    +-- NotImplementedError|    +-- SyntaxError 语法错误|    |    +-- IndentationError|    |         +-- TabError|    +-- SystemError|    +-- TypeError|    +-- ValueError  传给函数的参数类型不正确,比如给int()函数传入字符串形|         +-- UnicodeError|              +-- UnicodeDecodeError|              +-- UnicodeEncodeError|              +-- UnicodeTranslateError+-- Warning+-- DeprecationWarning+-- PendingDeprecationWarning+-- RuntimeWarning+-- SyntaxWarning+-- UserWarning+-- FutureWarning+-- ImportWarning+-- UnicodeWarning+-- BytesWarning
原创粉丝点击