Python Learning Notes (exception handling)

Source: Internet
Author: User

The user entered a non-compliant value, or the file that needs to be opened does not exist. These conditions are known as "exceptions", and a good program needs to be able to handle the exceptions that may occur, thus preventing the program from interrupting.

For example we go to open a file:

f = File (' Non-exist.txt ')

print ' File opened! '

F.close ()

If the file does not appear in the folder that should appear for some reason, the program will error:

IOError: [Errno 2] No such file or directory: ' Non-exist.txt '

The program is interrupted at the wrong place, and the subsequent print is not executed.

In Python, you can use the TRY...EXCEPT statement to handle exceptions. The idea is to put the statement that could throw the exception in the try-block and put the exception-handling statement in the except-block.

Put that piece of code into try...except:

Try

f = File (' Non-exist.txt ')

print ' File opened! '

F.close ()

Except

print ' File not exists. '

print ' Done '

When the program throws an exception while opening a file inside a try, it skips the rest of the code in the try and jumps directly to the statement handling exception in except. "File NOT exists." is then output. If the file is opened successfully, it will output "file opened!" instead of executing the statement in except.

However, the entire program will not be interrupted, and the last "done" will be output.

In a try...except statement, the exception thrown in a try is like throwing a frisbee, and except is a sensitive dog that always catches the frisbee accurately.

Python Learning Notes (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.