Introduction to Python exception handling and python exception handling

Source: Internet
Author: User

Introduction to Python exception handling and python exception handling

Python has powerful exception handling capabilities and can accurately report error information to users. In Python, exceptions are also objects that can be operated on. All exceptions are members of the base class Exception. All exceptions are inherited from the base class Exception and are defined in the exceptions module. Python automatically stores all the exception names in the built-in namespace, so the program does not need to import the exceptions module to use the exception. Python uses an exception object to indicate exceptions. An exception is thrown when an error occurs. If the exception object is not processed or captured, the program terminates the execution with the so-called trace (Traceback, an error message.

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.

1. keywords related to python exceptions

Raise: manually throw/raises an exception: raise [exception [, data]
Try/try t: capture and handle exceptions
Pass: Ignore exceptions
As: defines the abnormal instance (Response t IOError as e)
Finally: Code executed no matter whether an exception occurs]
Else: if the statement in try does not cause an exception, execute the statement in else.
Failed t Exception as error:

Ii. Exception types in python

1. StandardError class: this exception is thrown if a logic error occurs in the program. The StandardError class is the base class for all restrained exceptions and is placed in the default namespace. Therefore, classes such as IOEroor, EOFError, and ImportError are used and do not need to be imported into the exception module.

StopIteration class: determines whether the loop is executed to the end. If the loop ends to the end, this exception is thrown.
GeneratorExit class: An exception caused by the Generator function. This exception is thrown when close () is called.
Warning class: indicates the Warning caused by code in the program.

III. Basic Methods:

1. try:

Statement 1

Partition T [prediction1 (, exception2. ..), [data…] :

Statement 2

Else:

Statement 3

The exception handling syntax is as follows:

· Execute the statement in try. If an exception is thrown, the execution process jumps to the first t statement.

· If the exception defined in the first occurrence t matches the exception, the statement in the occurrence T is executed.

· If the exception does not match the first occurrence t, the second occurrence T will be searched, and there is no limit on the number of tokens allowed to be written.

· If all the counter t does not match, the exception will be passed to the top-level try code that calls this code next.

· If no exception occurs, execute the else block code.

import tracebacktry:  1/0except Exception as err:  print(err)try:  f = open("file.txt","r")except IOError as e:  print(e)try:  f = open("file.txt","r")except Exception as e:  print(e)

The last two outputs are exactly the same ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2. try:

Statement 1

Finally:

Statement 2

The statement execution rules are as follows:

· Execute the code in try.

· If an exception occurs, execute finally code when the exception is passed to the next try.

· If no exception occurs, execute the finally code.

The second try syntax is useful when code execution is required no matter whether an exception occurs. For example, if we open a file in python for read/write operations, I will close the file no matter whether an exception occurs during the operation. These two forms conflict with each other. If one is used, the other is not allowed, and the functions are different.

Therefore, in general, some cleanup tasks are executed in finally, such as disabling file descriptors and Releasing locks.

Note: In finally, if an exception occurs and the external body does not have a corresponding capture mechanism, the exception will be thrown layer by layer until the top, and the interpreter stops. Generally, try again at the outer layer to catch a try again t exception.

3. Manual use of raise causes an exception

1. raise [exception [, data]

2. In Python, to cause an exception, enter the keyword raise, followed by the name of the exception to be thrown. Exception names identify specific classes: Python exceptions are the objects of those classes. When a raise statement is executed, Python creates an object for the specified exception class. The raise statement can also specify the initialization parameters for the exception object. Therefore, add a comma and a specified parameter (or a tuple consisting of parameters) after the name of the exception class ).

3. instance:

Try: print ("Start test") raise IOErrorexcept IOError: print ("defined error") failed T: print ("other error ")

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.