"Python"--try except (Exception capture)

Source: Internet
Author: User

Try except (Exception capture)

When the program is wrong, but we do not want to let the user see this error, and I write the program has been expected that it can make such a mistake, the occurrence of such an error represents what, we can catch these errors ahead of time

1, exception processing flowchart:

2. Common anomalies
Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct
More Exceptions:
Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreoferror Exceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeyboardint Erruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningreferenceerr Orruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerrorunbou Ndlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarni Ngzerodivisionerror

3. Handling a single exception

The syntax is as follows:

Try:    code   #处理的语句except  Error1 as E:   #遇到Error1执行下面的语句, written in Python2 except  error1,e    print (e)

The code is as follows:

name = [1,2,3]try:    name[3]  #不存在3这个下标值except indexerror as E:   #抓取 indexerror This exception    print (e) #e是错误的详细信息 # Output list index out of range
4. Handling multiple exceptions

① write multiple except with the following syntax:

Try:    codeexcept Error1 as E:  #处理Error1异常    print (e) except Error2 as E:   #处理Error2异常    print (e)

The code is as follows:

name = [1,2,3]data = {"A": "B"}try:    data["C"]   #这边已经出现异常KeyError, so jump right out of code and skip to Keyerror to process    name[3] Except Indexerror as E:    print (e) except Keyerror as E:    print (e) #输出 ' C '

② writes 1 except with the following syntax:

Try:    codeexcept (Error1,error2,...) as E:    print (e)

The code is as follows:

Try:    data["C"]    name[3]except (indexerror,keyerror) as E:    print (e) #输出 ' C '

Note: The second way of writing is useful: all errors in parentheses, regardless of the occurrence of any one of the errors are used in a unified processing method.

5, exception abnormal

The syntax is as follows:

Try:    codeexcept (Error1,error2,...) as E:    print (e) except Exception as E:   #用Exception表示一下子抓住所有异常, This is generally recommended in the last face of the exception, with the last catch of the unknown exception    print (e)

The code is as follows:

Try:    open ("Qigao.text", "R", encoding= "Utf-8") except (Indexerror,keyerror) as E:   #没有IndexError, Keyerror These two exceptions    print (e) except Exception as E:  #只能通过这个异常处理, Exception catch all exceptions    print (e) #输出 [Errno 2] No such File or directory: ' Qigao.text '
6. Else role

Function: No exception, then go to the else part of the logic code

Try:    print ("Qigao,handson")    #代码没有异常except (Indexerror,keyerror) as E:    print (e) except Exception as E:    Print (e) Else:             #没有异常出错, go to Else's logic code    print ("no exception") #输出qigao, HandsOn no exception
7. Finnally Effect

Function: Executes code in finnally, regardless of error

The syntax is as follows:

Try:    codeexcept (Error1,error2,...) as E:    print (e) except Exception as E:    print (E) Else:    print ("No error, Execute ") finnally:    print (" Execute finnally whether or not it is wrong ")

  

① no abnormal conditions

Try:    print ("Qigao,handson")  #没有异常except (Indexerror,keyerror) as E:    print (e) except Exception as E:    Print (e) Else:    print ("no exception") Finally:    print ("No matter what is wrong, this line finnally") #输出qigao, HandsOn no exception, whether or not it is wrong, this line finnally  #没有报错, execute finnally

② abnormal conditions occur

Try:    data = {"A": "B"}    data["C"]   #data字典中没有 ' C ' This key value except (Indexerror,keyerror) as E:    print (e) Except Exception as E:    print (e) Else: print (    "no exception") Finally:    print ("Whatever is wrong, this line finnally") #输出 ' C ' whether or not it's wrong , all this line finnally   #出错了也执行了finnally语句

  

8. Custom Exceptions
Class Gaoerror (Exception):  #定义一个异常类, inheriting Exception     def __init__ (self,message):        self.message = message     def __str__ (self):        return self.message #给对象取一个名
To trigger a custom exception:
Try:    raise Gaoerror ("Database connection not on")  #触发自定义异常, Gaoerror ("Database connection is not on") this object except Gaoerror as E:    print (e) # The output database is not connected to the

Custom Usage Summary:

    1. Database connection not on the information
    2. Permission problem, parsing is no permission, give exception prompt
    3. Error in business logic

"Python"--try except (Exception capture)

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.