python--Exception Handling

Source: Internet
Author: User

The format in which Python handles exceptions is generally as follows:

Try

Part A

Except .... [As ...]:

Part B

[

Finally

Part C

Else:

Part D

]

Ps:

1, whether there is no exception, the finally part will be executed

2. If there is no exception, the else part will be executed

3, the number of except ≥1, if the exception Class A is the subclass of the exception Class B, then it is best to except a in front of except B, otherwise the exception class B directly intercept the subclass exception, will not execute to except a content

===============================================================================================

Raise manually throwing Exceptions

In Python, the simplest form of throwing an exception is to enter the keyword raise, followed by the name of the exception to throw. The exception name identifies the specific class: The Python exception is the object of those classes. When the raise statement is executed, Python creates an object of the specified exception class. The Raise statement can also specify parameters to initialize the exception object. To do this, add a comma after the name of the exception class and a specified parameter (or a tuple of parameters).

Try

Raise Exception class

Except exception class:

Part A

===============================================================================================

viewing exceptions using the Traceback () (Tracking) module

When an exception occurs, Python can "remember" the exception that is thrown and the current state of the program. Python also maintains a traceback (trace) object that contains information about the function call stack when an exception occurs. Remember that exceptions can be raised in a series of deep nested function calls. When the program calls each function, Python inserts the function name at the beginning of the function call stack. Once an exception is thrown, Python searches for a corresponding exception handler. If there is no exception handler in the current function, the current function terminates execution, Python searches the calling function of the current function, and so on, until a matching exception handler is found, or Python arrives at the main program. This process of finding the appropriate exception handler is called "Stack Kaixie" (Stacks unwinding). The interpreter maintains information about functions in the placement stack, and on the other hand maintains information about functions that have been "Kaixie" from the stack.

Format:

Try
Block
Except
Traceback.print_exc ()

Example: ... excpetion/traceback.py

===============================================================================================

Using the SYS module to retrace the last exception

Import Sys
Try
Block
Except
Info=sys.exc_info ()
Print info[0], ":", info[1]

Or in the following form:

Import Sys
TP,VAL,TD = Sys.exc_info ()

The return value of Sys.exc_info () is a tuple, (type, value/message, Traceback)

Type of----exception here

Value/message----Information or parameters of an exception

The Traceback----The object that contains the call stack information.

From this point, it can be seen that this method covers the Traceback.

===============================================================================================

Pre-defined cleanup behavior

Some objects define the standard cleanup behavior, regardless of whether the system successfully uses it, and once it is not needed, the standard cleanup behavior is performed.

This example shows an attempt to open a file and then print the content to the screen:

for on open("MyFile.txt"):print(line,end="") 

The problem with the above code is that when execution is complete, the file remains open and is not closed.

The keyword with statement will ensure that objects such as files are used to perform their cleanup correctly after they are exhausted:

With open("MyFile.txt")as F: For in f:print( Line ,End="")               

When the above code is executed, the file F is always closed, even if there is a problem during processing.

python--Exception Handling

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.