Python topic-Exception Handling (basic) and python exception handling

Source: Internet
Author: User

Python topic-Exception Handling (basic) and python exception handling

I have previously compiled an article about python exception handling when I was learning python. It is not simple enough or complete enough. So I decided to write another article to supplement it.

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

 

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 an existing abc.txt file. When the system cannot find the abc.txt file, an IOError type error will be thrown to us, No such file or directory: abc.txt (without a file or directory such as abc.txt)

 

Try... Try t...

 

If we already know this type of error, we can catch it with an exception. We can use try... retry t to receive this error. Open file write:

try:    open("abc.txt",'r')except IOError:    pass 

If you run the program again, you will not see any errors, because we have received this IOError error with the handle T. Pass indicates that the corresponding implementation is implemented, but nothing is done.

What if I output an undefined variable instead of opening a file?

try:    print  aaexcept IOError:    pass 

Obviously, in the above code, I did not assign a value to aa. The running result is:

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

We have already received the error using the handle T. Why is the error still thrown. If you are careful, you will find that this error type is NameError and I receive the IOError type. To receive this print error, You need to modify the type of the received error to NameError.

Although I know that the print statement may throw a NameError type error, although I have received this type error, I do not know the specific error message. So, can I print out the error information? Of course:

try:    print  aaexcept  NameError, msg:    print  msg

After receiving error types, we define a variable msg to receive specific error messages and print the error messages received by msg. Run the program again:

name 'aa' is not defined

Only a specific error message is printed.

Exception throw mechanism:

1. if an exception occurs during running, the interpreter looks for the corresponding processing Statement (handler ).

2. If it is not found in the current function, it will pass the exception to the upper-layer call function to see if it can be processed.

3. If it is still not found in the outermost layer (global "main"), the interpreter will exit and print traceback to help you find the cause of the error.

 

Note: although most errors may cause exceptions, an exception does not necessarily mean errors. Sometimes they are only a warning, and sometimes they may be a termination signal, such as an exit loop.

 

 

Try... finally...

 

Try... finally... clause is used to express the following situation:

We do not track what errors are caught, no matter whether the errors occur or not, these codes are "required" to run, such as closing the file, releasing the lock, and returning the database connection to the connection pool.

Create a file poem.txt

Tryf. py

import timetry:    f = file('poem.txt')    while True: # our 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 (run at a windows Command Prompt or a 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 the data of each row in the poem.txt file and prints the data, but I tried to pause the data for 2 seconds by using the time. sleep method before each row is printed. The reason for doing so is to make the program run slowly. When running the program, press Ctrl-c to interrupt/cancel the program.

We can observe that the KeyboardInterrupt exception is triggered and the program exits. However, before the program exits, the finally clause is still executed to close the file.

 

 

So far, we have only discussed how to capture exceptions and how to 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 !')

The program requires the user to enter a file name. If the user input the file name is hello, A NameError exception is thrown. There is no necessary link between the user input hello and NameError exceptions, I just defined it manually through raise. Of course, TypeError can also be defined, but the exception type I defined must be provided by python.

 

Appendix:

Common python exception types

Related Article

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.