Python Notes-Exception handling

Source: Internet
Author: User

Exception handling

Exception is the program error does not work properly, exception handling is through a number of methods to capture the error occurred, friendly display or appropriate processing, so that the program can run longer.

1. type of exception

Common:

SyntaxError Syntax error

Indentationerror Indent Error

TypeError Object type does not conform to requirements

Importerror Module or package import error; generic path or name error

Keyerror keys that do not exist in the dictionary

Nameerror variable does not exist

Indexerror subscript out of sequence range

IOError input / output exception, usually cannot open file

There are no attributes in the Attributeerror object

Keyboardinterrupt keyboard accepted to CTRL + C

Exception generic exception type; Generally catches all exceptions

See all of the exception types:

>>> import exceptions>>> dir (exceptions) [' Arithmeticerror ',  ' Assertionerror ',  ' attributeerror ',  ' baseexception ',  "Buffererror ',  ' BytesWarning ',  ' Deprecationwarning ',  ' eoferror ',  ' environmenterror ',  ' Exception ',,  ' floatingpointerror ',   ' futurewarning ',  ' generatorexit ',  ' IOError ',  ' importerror ',  ' importwarning ',  ' Indentationerror ',  ' indexerror ',  ' keyerror ',  "Keyboardinterrupt ',  ' LookupError ',  ' Memoryerror ',  ' nameerror ',  ' notimplementederror ',  "OSError ',  ' overflowerror ',  ' Pendingdeprecationwarning ',  ' referenceerror ',  ' runtimeerror ',  ' runtimewarning ',  ' StandardError ',  ' stopiteration ',  ' syntaxerror ',  "syntaxwarning ',  ' SystemError ',  ' Systemexit ',  ' taberror ',  ' TypeError ',  "Unboundlocalerror ',  ' unicodedecodeerror ',  ' Unicodeencodeerror ',  ' unicodeerror ',  ' UniCodetranslateerror ',  ' unicodewarning ',  ' userwarning ',  "ValueError ',  ' Warning ',  ' Windowserror ',  ' zerodivisionerror ',  ' __doc__ ',  ' __name__ ',  ' [__package__ ']

2. Catching exception Syntax

Try:pass #被检查的语句except except Type,e: #except type indicates the kind of exception to catch, E is a variable, and the exception information is saved. Pass # ", E" can be written as "E"

For example:

>>> Try:print a #a是一个未定义的变量, directly execute "print a" will report Nameerror exception except Nameerror,e:print "Error:", e error:name ' a ' is n OT defined

Attention:

Multiple except can be written if the exception can occur in more than one category. For example:

>>> a = ' Hello ' >>> try:int (a) except Indexerror,e:print eexcept keyerror,e:print eexcept Valu Eerror,e:print E

If you do not know what is going to happen, you can use exception to catch any exception, for example:

>>> a= ' Hello ' >>> try:int (a) except Exception,e:print E

If the exception is not caught and the exception type does not match, the program directly error, for example:

>>> a= ' Hello ' >>> try:b=int (a) except Indexerror,e:print e Traceback (most recent call last): File "< Pyshell#27> ", line 2, in <module> B=int (a) valueerror:invalid literal for int. () with base: ' Hello '

Other structures to catch exceptions:

#else语句

Try:pass #主代码块except Keyerror,e:passelse:pass # The main code block executes without exception, executing the block.

#finally语句

Try:pass #主代码块except Keyerror,e:passfinally:pass # no matter the exception or not, the block is eventually executed.

#try/except/else/finally Combined statements, it is important to note that the else and finally are placed after except , and finally is placed at the end.

Try:passexcept Keyerror,e:passelse:passfinally:pass

4. proactively triggering exceptions

Raise can actively throw an exception, for example:

>>> Raise Nameerror (' This is a Nameerror ') Traceback (most recent call last): File "<pyshell#2>", line 1, In <module> raise Nameerror (' a nameerror ') Nameerror:this is an nameerror

#捕捉主动触发的异常

>>> try:raise Exception (' ERROR!!! ') Except Exception,e:print e error!!!

5. Custom Exceptions

>>> class myexception (Exception):      #继承Exception类     def __init__ (self,msg):            #使用Exception类的__init__方法         self.message= msg              #添加一个 "message" Property for storing error messages     def __str__ (self):        return  Self.message >>> try:    raise myexception ("myerror!")      #主动引发自定义异常except  MyException,e:         print e myerror! 

6. Assert statement assert

Assert is used to determine whether a conditional judgment statement is true or not, and it is not true to punish an exception, for example:

>>> assert 2>1>>> assert 2<1traceback (most recent): File ' <pyshell#22> ', line 1, In <module> assert 2<1assertionerror

#添加异常描述信息:

>>> assert 2<1, "flase" Traceback (most recent call last): File "<pyshell#23>", line 1, in <module>    ; Assert 2<1, "flase" assertionerror:flase

This article is from the "Network Technology" blog, please be sure to keep this source http://fengjicheng.blog.51cto.com/11891287/1929107

Python Notes-Exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.