Python Exception handling

Source: Internet
Author: User

Python uses a try statement to implement exception handling. A try statement surrounds other statements that might throw an exception. The try statement begins with a keyword try, followed by a colon (:) and a code that may throw an exception in it. The Try statement can specify one or more except clauses that are immediately after the try suite. Each except clause specifies 0 or more exception class names that represent the type of exception to be handled by the EXCEPT clause. You can specify a marker in the EXCEPT clause that the program uses to refer to the caught exception object. Handlers take advantage of identifiers to get information about exceptions from exception objects. If the exception type is not specified in the EXCEPT clause, it is called a "blank except clause." This seed sentence captures all exception types . After the last except clause, you can optionally add an else clause. If the code in try suite does not throw an exception, the code in the ELSE clause is executed. If the try statement does not specify a except clause, it must contain a finally clause----the clause will certainly execute, regardless of whether an exception occurs.

including both the except and the finally clauses in a try statement is a syntax error, and the accepted combinations are only:

1Try:            ...... # could get an exception to the statement     Except#What kind of exception is locked?except  Exception,e:#捕获所有异常    ...... # handling of unusual occurrences  2Try:    ......   except    .......   Else    ......3Try:    ......  finally    ........

Once the program code causes an exception, or the Python interpreter detects a problem, the code or interpreter "throws" an exception. Some programmers refer to the location where the exception occurred in the program as the "Trigger point". exceptions are objects of classes that are inherited from the exception class . If an exception occurs in a try suite, the try suite immediately "timed out" (that is, immediately terminated), and the program control is handed over to the first except handler (if any) after try suite. The interpreter then searches for the first except handler that can handle this type of exception. To determine the matching except, the interpreter needs to compare the type of exception that is thrown with the exception type of each except handler until the final discovery matches. If the type is exactly the same, or if the type of the exception that is thrown is a derived class of the exception type of the except handler, it indicates that a match has occurred. If no exception occurs in try suite, the interpreter ignores the exception handler for the Try statement and executes the ELSE clause (if any) of the try statement. If no exception occurs, or if an except clause succeeds in handling the exception, the program resumes execution from the next statement after the try statement. If an exception occurs in a statement, but the statement is not in a try suite, but in a function, then the function that contains that statement terminates immediately, and the interpreter attempts to find a closed try statement in the (emitted) call code, a process called "Stack Kaixie" ( Stacking unwinding).

----------------------------------------------------------------------------------------------

Python shell

>>> open (' Abc.txt ', ' R ') Traceback (most recent call last):  File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: ' Abc.txt '

Open a nonexistent file Abc.txt file, when the system can not find the Abc.txt file, will be thrown to us a ioerror type of error, no such file or directory:abc.txt (no abc.txt such as files or directories)

Try...except ...

If we already know this type of error, then we can catch the error by catching it with an exception. We can accept this error by try...except. Open File Write:

Try:    open ("Abc.txt", ' R ') except IOError:    

Running the program again will not see any errors, because we receive this ioerror error with except. Pass means that the implementation is implemented, but nothing is done.

What if I'm not opening a file, I'm outputting a variable that doesn't have a definition?

Try:    print  aaexcept IOError:    

Obviously, in the above code I did not assign a value to AA, running the result:

Traceback (most recent):  File "/home/fnngj/py_se/tryy.py", line 3, in <module>    print  Aanameerror:name ' AA ' is not defined

We have used except to receive the error, and why the error is still thrown out. If you are careful to find that this time the error type is Nameerror, and my receive type is ioerror, so to receive this print error, then need to modify the type of receive error Nameerror

Although, I know that the print statement is likely to throw a Nameerror type error, although I received this type error, I do not know what the specific error message is. So, can I print out the wrong information? Of course:

Try:    print  aaexcept  nameerror, msg:    print  msg

We define a variable msg after receiving the type of error to receive the specific error message and then print the error message received by MSG. To run the program again:

Name ' AA ' is not defined

Only one line of specific error messages is now printed.

Exception throwing 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 allow the user to find the cause of the error.

Note: Although most errors cause exceptions, an exception does not necessarily represent an error, sometimes they are just a warning, and sometimes they may be a terminating signal, such as exiting a loop.

Try...finally ...

Try...finally ... Clauses are used to express such situations:

We do not catch the pipeline what error, regardless of whether the error occurs, the code "must" run, such as file shutdown, release the lock, the database connection to the connection pool and so on.

Create File Poem.txt

tryf.py

Import Timetry:    f = file (' Poem.txt ') while    True: # We usual file-reading idiom line        = F.readline ()        If Len (line) = = 0: Break        Time.sleep (2)        print line,

Finally: f.close () print ' Cleaning up...closed the file '

Run the program (running under Windows command prompt or Linux terminal):

... $ python tryf.py abcefg^ccleaning up...closed The Filetraceback (most recent call last):  File ' tryy.py ', line 18, In <module>    time.sleep (2) Keyboardinterrupt

The program reads each row of data in the Poem.txt file, but I intentionally pauses for 2 seconds with the Time.sleep method before each line is printed. The reason for this is to make the program run slower. When the program is running, press Ctrl-c to break/Cancel the program.

We can observe that the keyboardinterrupt anomaly is triggered and the program exits. But before the program exits, the finally clause is still executed and the file is closed.

So far, we've only discussed how to catch exceptions, so how do we throw exceptions?

Raise throws an exception

use raise to throw an exception: to throw an exception, to let the program stop, you can actively throw an exception, compared to exit: There are clear reasons

tryr.py

#coding =utf-8filename = raw_input (' Please input file name: ') if filename== ' Hello ':    nameerror(' input file Name Error! ')

The program requires the user to enter a file name, if the user entered a file name is Hello, then throws a Nameerror exception, the user input Hello and nameerror exception between no inevitable connection, I just man through raise to define this, I can certainly define TYPEERROR, but the exception types I define must be python-supplied.

Appendix:

Common Python exception types

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.