Python Exception handling

Source: Internet
Author: User

I. INTRODUCTION

In order to increase the friendliness in the programming process, the error message is usually not presented to the user directly when the program bug occurs, but provides a friendly output hint.

Two. Use

1. Exception Basics

Common structure:

Try:    passexcept exception,ex:    Pass

Other structures:

Try:    # main code block    passexcept keyerror,e:    # Exception when executing the block    passelse:    # The main code block executes, executes the block    passfinally:    # Whether abnormal or not, the final execution of the block    Pass

2. Type of exception

#  Common Exception Types Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo does not have a property xioerror input/output exception; it is basically impossible to open the file Importerror the module or package cannot be introduced is basically a path problem or name error Indentationerror syntax error (subclass); The code is not aligned correctly indexerror the subscript index exceeds the sequence boundary, for example, when X has only three elements, it attempts to access the X[5]keyerror Attempting to access a key that does not exist in the dictionary Keyboardinterrupt CTRL + C is pressed Nameerror use a variable that has not been assigned to the object SyntaxError Python code is illegal, the code cannot compile (personally think this is a syntax error, Wrong) TypeError the incoming object type is not compliant with the requirements Unboundlocalerror attempts to access a local variable that is not yet set, basically because another global variable with the same name causes you to think that you are accessing it valueerror a value that the caller does not expect , even if the type of the value is correct

3. Multiple exception captures

Try:    passexcept indexerror,e:    passexcept keyerror,e:    passexcept valueerror,e:    Pass

4. Universal Anomaly Capture

Try:    passexcept  exception,e:    Pass

Question: Now that we have a universal exception, do we need a single exception capture or a multiple exception capture?

Self-answer: Many scenarios we need to identify the type of anomaly, according to the type of anomaly can quickly locate the cause of the anomaly. If all exceptions are caught with a universal exception, although it avoids the program throwing ugly exceptions, but also can not help us solve the problem, the common idea is that for special exceptions we do a separate error, and other exceptions can be ignored with the universal exception handling.

S1 = ' Hello ' try:    int (s1) except Keyerror,e:    print (' key error ') except Indexerror,e:    print (' index error ') except Exception, E:    print (' ERROR ')

5. Custom Exceptions

Class MyException (Exception):     def __init__ (self, msg):        self.message = msg     def __str__ (self):        return Self.message try:    raise MyException (' my exception ') except Myexception,e:    print (e)

6. Proactively triggering exceptions

Try:    raise Exception (' wrong ... ') except Exception,e:    print (e)

7. Assertions

# condition is not error, and error # assert condition assert 1 = = 1        # condition is established, then continue to execute the following code assert 1 = = 2        # condition is not established, then error

 

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.