Introduction to five exception handling mechanisms in Python

Source: Internet
Author: User
Learning programming from a few years ago until now, the exception handling in the program has a fear and rejection mentality. This is because it is not understood. This attack on Python, first of all the most feared and the most unfamiliar pieces of content listed, there is "exception handling" this item.

"Dive into Python" does not specifically describe exception handling, but it is only a little bit illustrative when used in the example. Download "Learn Python" today and go directly to the exception handling this piece. This section has four chapters, the first chapter explains the general use method of exception handling, and later chapters discuss its mechanism in depth. I have only read the first chapter, the first to learn to use, and later when necessary to expand reading.

Python mainly supports five kinds of anomaly mechanisms, listed.

The default exception handler

The code is as follows:


s = ' Hello girl! '
Print s[100]
print ' Continue '

If we do not prevent any exceptions, then an exception occurs during the execution of the program, it interrupts the program, invokes the Python default exception handler, and outputs the exception information at the terminal. In this case, the 3rd line of code will not execute.

Try...except

The code is as follows:


s = ' Hello girl! '
Try
Print s[100]
Except Indexerror:
print ' Error ... '
print ' Continue '

When the program executes to the 2nd sentence, it discovers a try statement, enters the try statement block execution, takes exception, returns to the Try statement layer, and looks for a except statement behind it. When the except statement is found, this custom exception handler is called. Except after the exception is processed, the program continues to execute down. In this case, the last two print statements will be executed.

Except can also be empty later, indicating that any type of exception is caught.

Try...finally

The code is as follows:


s = ' Hello girl! '
Try
Print s[100]
Finally
print ' Error ... '
print ' Continue '

The finally statement indicates that the statements in finally are executed regardless of whether the exception occurred. However, because there is no except processor, the program is interrupted after finally execution is complete. In this case, the 2nd print will be executed, and the 1th will not be executed. If there is no exception in the Try statement, three print will execute.

Assert

The code is as follows:


Assert False, ' Error ... '
print ' Continue '

This statement, first to determine whether the statement immediately after the assert is true or false, if true, proceed to print, if False, break the program, call the default exception handler, and output the message after the Assert statement comma. In this case, the program is interrupted, prompting for error, and subsequent print does not execute.

With...as

The code is as follows:


With open (' Nothing.txt ', ' R ') as F:
F.read ()
Print 2/0
print ' Continue '

When we use a Stream object like a file, it is cumbersome to call the Close method when it is finished. The WITH...AS statement here provides a handy workaround: Open opens the file and assigns the returned file stream object to F, which is then used in the WITH statement block. After the WITH statement block is complete, the file is automatically closed.

If an exception occurs in a with statement or statement block, the default exception handler is invoked, but the file is closed gracefully.

In this case, an exception is thrown, and the last print is not executed.

The book is described in detail, in addition to what I mentioned above, there are a lot of useful additional information, such as try. Except. Finally.. Else can be used with, for example, custom exception classes. No longer listed here, please refer to the introduction in this book for details.

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