Python topic-Exception handling (Basic)

Source: Internet
Author: User

  Before learning Python, there have been a series of Python exception handling articles, not simple enough and incomplete, so decided to tidy up an article, to do a supplement.

Http://www.cnblogs.com/cmt110/p/7464748.html

Python shell

 >>> Open ( ' abc.txt  ", " r ' abc.txt"     

Open a nonexistent file abc.txt file, when the system cannot find the abc.txt file, it will throw us a ioerror type of error, No such file or directory:abc.txt (no files or directories such as Abc.txt)

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      

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     

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

Traceback (most recent):  "/home/fnngj/py_se/tryy.py in<module>    print' AA notdefined      

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 you can:

Try:    print  aaexceptprint 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:

'AA notdefined 

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

ImportTimeTry: F = file ( ' poem.txt ' ) while True: # Our usual file-reading idiom line = F.readline () if len (line) == 0: break< Span style= "COLOR: #000000" > Time.sleep (2print 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):  "tryy.py  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, thefinally 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:

tryr.py

 #coding=utf-8filename = raw_input ( ' please input file Name: ' " if filename==hello ": raise nameerror (" input file name error!< Span style= "COLOR: #800000" ")            

  The program requires the user to enter a file name, if the user entered the file name is Hello , then throws a nameerror exception, the user input Hello and nameerror exception between no inevitable contact, I just man through Raise to define this, I can of course define the name TypeError , but the exception type I define must be python -supplied.

Appendix:

Common Python exception types

Python topic-Exception handling (Basic)

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.