Python exception handling

Source: Internet
Author: User

#! /Usr/bin/Python

Import traceback
Try:
1/0
# Failed t exception, E:
# Print traceback. format_exc ()

Failed t exception as E:
Print E

#! /Usr/bin/Python
Import traceback
Try:
1/0
# Failed t exception, E:
# Print traceback. format_exc ()

Except t exception, E:
Print E

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. Once the system exit exception is thrown and not caught, the program execution ends. If an uncaptured systemexit exception occurs in an interactive session, the session ends.

Method 1: Try statement:

1. Use try and try t statements to capture exceptions

Try:
Block
Failed T [exception, [data…] :
Block

Try:
Block
Except T [exception, [data...]:
Block
Else:
Block

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.

Example:

Try:

F = open(‑file.txt "," R ")
Handle t ioerror, E:
Print E

The detailed cause of the captured ioerror will be placed in Object E, and then run the failed T code block of the exception.

Capture all exceptions

Try:
A = B
B = C
Failed t exception, EX:
Print exception, ":", ex

Note that when an exception is intercepted by multiple distinct T clauses, if there is an inheritance relationship between the exception classes, the subclass should be written in front, otherwise, the parent class directly intercepts the subclass exception. The sub-class exception that is placed below will not be executed.

2 use try and finally:

Syntax:

Try:
Block
Finally:
Block

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.

2. Manually raise an exception using the raise statement:

Raise [exception [, data]

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

Example:

Try:
Raise myerror # throw an exception
Failed t myerror:
Print 'a error'

Raise valueerror, 'invalid argument'
The captured content is:

Type = vauleerror
Message = invalid argument

3. Use the traceback module to view exceptions.

When an exception occurs, python can "remember" The exceptions and the current state of the program. Python also maintains traceback (TRACE) objects, which contain information related to the function call stack when an exception occurs. Remember, exceptions may be thrown in a series of nested deep function calls. When a 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 an exception handler. If no exception handler exists in the current function, the current function is terminated, and Python searches for the calling function of the current function, and so on until a matched exception handler is found, or Python arrives at the main program. This process of finding a suitable exception handler is called "Stack unwinding ). On the one hand, the interpreter maintains information related to the functions placed in the stack, and on the other hand, it maintains information related to the functions that have been "rolled out" from the stack.

Format:

Try:
Block
Except t:
Traceback. print_exc ()

Example :... Excpetion/traceback. py

4. Use the SYS module to trace the final exception

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

Or in the following format:

Import sys
TP, Val, TD = SYS. exc_info ()

SYS. exc_info () returns a tuple (type, value/message, traceback)

Type here ---- exception type

Value/message ---- exception information or parameters

Traceback-the object that contains the call stack information.

From this point, we can see that this method covers traceback.

5. Other functions of Exception Handling

In addition to handling actual error conditions, there are many other functions for exceptions. A common usage in the standard Python library is to import a module and check whether it can be used. Importing a module that does not exist will cause an importerror exception. You can use this method to define multi-level functions-depending on which module is valid at runtime or supports multiple platforms (that is, platform-specific code is separated into different modules ).

You can also define your own exceptions by creating a class inherited from the built-in exception class, and then use the Raise command to raise your exceptions. If you are interested in this, please read more.

The following example demonstrates how to use exceptions to support specific platform functions. The Code comes from the getpass module, a encapsulation module that obtains the password from the user. The implementation of the obtained password on UNIX, windows, and Mac OS platforms is different, but this Code encapsulates all the differences.

For example, platform-specific functions are supported.

# Bind the name getpass to the appropriate Function

Try:
Import termios, termios
Failed t importerror:
Try:
Import msvcrt
Failed t importerror:
Try:
From easydialogs import askpassword
Failed t importerror:
Getpass = default_getpass
Else:
Getpass = askpassword
Else:
Getpass = win_getpass
Else:
Getpass = unix_getpass

Termios is a unique UNIX module that provides underlying control over input terminals. If this module is invalid (because it is not on your system, or your system does not support it), the import fails, and Python triggers the importerror exception.

OK, we don't have termios, so let's try msvcrt. It is a unique module in windows and can provide an API for many useful functions in Microsoft Visual C ++ running services. If the Import fails, python will cause an importerror exception.

If the first two do not work, we try to import a function from easydialogs, which is a unique module of Mac OS and provides various types of pop-up dialog boxes. Once again, if the Import fails, python will cause an importerror exception that we captured.

None of these platform-specific modules are valid (probably because Python has been transplanted to many different platforms ), so we need to use a default password input function (this function is defined elsewhere in the getpass module ). Note what we have done here: we assign the default_getpass function to the variable getpass. If you read the official getpass document, it will tell you that the getpass module defines a getpass function. It does this: bind getpass to the correct function to adapt to your platform. Then, when you call the getpass function, you actually call the platform-specific function. This Code has already been set for you. You do not need to know or care about the platform on which your code is running. If you call getpass, it can always be handled correctly.

A try... limit t block can have an else clause, just like an if statement. If no exception is thrown in the try block, the else clause is executed. In this example, it means that if the import from easydialogs import askpassword can work, we should bind getpass to the askpassword function. Each Other try... example t block has a similar else clause. When we find that an import is available, we bind getpass to the appropriate function.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/JINXINXIN_BEAR_ OS /archive/2011/02/23/6202784.aspx

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.