Python Exception handling

Source: Internet
Author: User

exception-throwing mechanism: provides program developers with the ability to run error discovery, perform recovery processing, and then continue execution.


Example:

>>> try: F = open (' unfile.py ', ' r ') ... except IOError, E: ... print False, str (e) ... False [Errno 2] No such file or directory: ' unfile.py '


#!/usr/bin/pythontry: #try尝试执行代码 open (' Abc.log ') except ioerror,msg: #except接受异常, notice that the name of the exception matches, and pass the exception message through the variable #占位

#执行代码时没有任何问题, but this code is not open.

*msg variable interpretation, just accept the wrong message:

Except Ioerror,msg:print msg after executing code, print related error [Errno 2] No such file or directory: ' Abc.log '


#如果直接执行:

Open (' Abc.log ') #报错: Traceback (most recent): File "try.py", line 6, in <module> open (' Abc.log ') IOError: [Errno 2] No such file or directory: ' Abc.log '

Exception Type Note: exception type, not directly using except can catch exceptions;

[email protected] 123]# cat try.py #!/usr/bin/pythontry:open (' Abc.log ') except nameerror,msg:  #当修改异常类型为NameError pass[[email protected] 123]# python try.py Traceback (most recent call last): File "try.py", Line 3, in <module> open (' Abc.log ') IOError: [Errno 2] No such file or directory: ' Abc.log '

#执行后IOError同样会报错, except did not capture Nameerror

#如果有多段代码

[[email protected] 123]# cat try.py #!/usr/bin/pythontry:open (' Test.log ') #此处的test. log file is present in print H Ello #此处的hello是一个变量, not string except Ioerror,msg:pass[[email protected] 123]# python try.py Traceback ( Most recent: File "try.py", line 4, <module> print hellonameerror:name ' hello ' are not defined
#当执行到hello时, the hint is not named;

implied: When an exception occurs, the program terminates, then catches the exception, and if the exception is repeated, it can be captured again

[[email protected] 123]# cat try.py #!/usr/bin/pythontry:open (' Test.log ') print helloexcept Ioerror,msg:passexc EPT nameerror,msg:pass[[email protected] 123]# python try.py
#当再次执行时, the anomaly is obscured.

#再次强调异常的捕获, is defined by the name of the exception!

Exception Handling: Pass just hides the exception, not nothing else, (such as defining some function of exception handling to solve the problem)!

Example:

[[email protected] 123]# cat try.py #!/usr/bin/python#coding:utf8filename = raw_input ("Please enter the file to be manipulated:") try:open (filename) Print Hellpexcept ioerror,msg:print "The specified file does not exist, please re-enter the" except Nameerror,msg:print "Internal variable call Error!" [[email protected] 123]# python try.py Please enter the file you want to manipulate: Test.log internal variable call Error! [[email protected] 123]# python try.py Please enter the file you want to manipulate: A.log The specified file does not exist, please re-enter # to handle the program segments that may have problems, capture the problem and handle it accordingly.

Throw mechanism:

1. If an exception occurs at run time, the interpreter will find the appropriate processing statement (called handler)

2, if not found in the current function, it will pass the exception to the upper call function, to see if it can handle.

3. If the outermost (global "main") is not found, the interpreter exits and prints out the traceback to let the user find out why the error occurred.

#注意虽然大多数错误会导致异常, but an exception does not necessarily represent an error. Sometimes they are just a warning, sometimes they may be a terminating signal, such as exiting a loop.


Finally sentence:

Python provides the try-finally clause, which expresses: does not care about the catch error, and whether the error occurs, the code must be executed, such as the closing of the file, releasing the lock, returning the database link to the link pool, etc.

Problem:

#!/usr/bin/python#coding:utf8filename = raw_input ("Please enter the file to be manipulated:") try:    f =  open (filename)                                       print hellpexcept IOError,msg:    print  "The specified file does not exist, please re-enter" except nameerror,msg:    print  "Internal variable call Error!" print  "Over" f.close () print  "that ' S all" [[email protected] 123]# python  try.py  Please enter the file you want to manipulate:123                              #此处f对象是无指定的文件不存在, Please re-enter overtraceback  (most recent call last):  file  "try.py", line  12, in <module>    f.close () &Nbsp;                                       #执行时出现问题NameError: name  ' F '  is not defined

Example:

#!/usr/bin/python#coding:utf8filename = raw_input ("Please enter the file to be manipulated:") try:f = open (filename) print hellpexcept ioerror,msg : print "The specified file does not exist, please re-enter" except Nameerror,msg:print "Internal variable call Error!" Finally:print "OK" [[email protected] 123]# python try.py Please enter the file you want to manipulate: 123 The specified file does not exist, please reenter the ok# note the finally clause executes

Raise throws an exception:

Example:

#!/usr/bin/python#coding:utf8filename = raw_input ("Please enter the file to be manipulated:") try:f = open (filename) print hellpexcept ioerror,msg : print "The specified file does not exist, please re-enter" except Nameerror,msg:print "Internal variable call Error!" Finally:print "OK" if filename = = "Hello": Raise TypeError ("noting!!!")
[[email protected] 123]# python try.py Please enter the file you want to manipulate: New.log internal variable call error!ok[[email protected] 123]# python try.py Please enter the file you want to manipulate: Hello specified file does not exist, please re-enter Oktraceback (most recent call last): File "try.py", line +, in <module> raise Type ERROR ("noting!!!") Typeerror:noting!!! #此处抛出异常

Note: The type of exception can not be arbitrarily specified, you need to be able to identify in Python, normal handling of exceptions.

Such as:

... if filename = = "Hello": Raise Othererror ("noting!!!") After execution: Traceback (most recent call last): File "try.py", line +, in <module> raise Othererror ("noting!!!") Nameerror:name ' Othererror ' is not defined

Common Python Exceptions:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/6E/3B/wKiom1V2rviCTu6-AAQU5p8hS-0629.jpg "title="}9mkjk {_3] [2_1 ' W9] a9@ (a.jpg "alt=" Wkiom1v2rvictu6-aaqu5p8hs-0629.jpg "/>




This article from "thinking More than technology" blog, declined reprint!

Python 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.