Python exception handling [go]

Source: Internet
Author: User
Tags terminates

#!/usr/bin/python

Import Traceback
Try
1/0
#except exception,e:
# Print Traceback.format_exc ()

Except Exception as E:
Print E

#!/usr/bin/python
Import Traceback
Try
1/0
#except exception,e:
# Print Traceback.format_exc ()

Except Exception, E:
Print E

Python's exception handling capability is powerful, providing users with accurate feedback on error messages. In Python, an exception is also an object that can be manipulated. 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 places all exception names in the built-in namespace, so the program does not have to import the exceptions module to use exceptions. Once thrown and not caught Systemexit exception, program execution terminates. If the interactive session encounters an Systemexit exception that is not caught, the session terminates.

Mode one: Try statement:

1 using try and except statements to catch exceptions

Try
Block
Except [Exception,[data ...]:
Block

Try
Block
Except [Exception,[data ...]:
Block
Else
Block

The rules for this type of exception handling syntax are:

· Executes the statement under try, and if an exception is thrown, the execution skips to the first except statement.

· If the exception that is defined in the first except matches the exception that is thrown, the statement in the except is executed.

· If the exception that is thrown does not match the first except, the second except is searched, and the number of except allowed to be written is unlimited.

· If all except do not match, the exception is passed to the next highest-level try code that calls this code.

· If no exception occurs, the else block code is executed.

Cases:

Try

f = open ("file.txt", "R")
Except IOError, E:
Print E

The detailed cause of the captured IOError error is placed in Object E, and then the except code block that runs the exception

Catch all the exceptions

Try
A=b
B=c
Except Exception,ex:
Print Exception, ":", ex

The thing to note with the EXCEPT clause is that when multiple except clauses intercept an exception, if there is an inheritance relationship between each exception class, the subclass should be written in front, otherwise the parent class will intercept the subclass exception directly. The sub-class exception that is placed in the back will not be executed.

2 using try and finally:

The syntax is as follows:

Try
Block
Finally
Block

The execution rules for this statement are:

· Executes the code under try.

· If an exception occurs, the code in the finally is executed when the exception is passed to the next-level try.

· If no exception occurs, the code in finally is executed.

The second try syntax is useful if you want to execute code regardless of whether an exception occurred. For example, we open a file in Python for read and write operations, I in the process regardless of whether or not an exception, the end is to put the file closed.

These two forms conflict with one another and are not allowed to use the other, and the function is different.

2. Manually throw an exception with the Raise statement:

raise [Exception[,data]]

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

Cases:

Try
Raise Myerror #自己抛出一个异常
Except Myerror:
print ' A error '

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

Type = Vauleerror
message = Invalid argument

3. Use the Traceback (tracking) module to view exceptions

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

4. Using the SYS module to backtrack to 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.

5. Some other uses of exception handling

In addition to dealing with the actual error conditions, there are many other uses for exceptions. A common use in a standard Python library is to try to import a module and then check if it can be used. Importing a module that does not exist throws a Importerror exception. You can use this method to define multiple levels of functionality-depending on which module is valid at run time, or to support multiple platforms (that is, the platform-specific code is separated into different modules).

You can also define your own exception by creating a class that inherits from the built-in Exception class, and then use the Raise command to throw your exception. If you are interested in this, see the section on further reading.

The following example shows how to use exceptions to support specific platform features. The code comes from the Getpass module, a package module that obtains the password from the user. The implementation of getting passwords on UNIX, Windows, and Mac OS platforms is different, but this code encapsulates all the differences.

Example supports specific platform features

# Bind The name Getpass to the appropriate function

Try
Import Termios, Termios
Except Importerror:
Try
Import MSVCRT
Except Importerror:
Try
From easydialogs import Askpassword
Except Importerror:
Getpass = Default_getpass
Else
Getpass = Askpassword
Else
Getpass = Win_getpass
Else
Getpass = Unix_getpass

The Termios is a UNIX-only module that provides the underlying control of the input terminal. If this module is not valid (because it is not on your system, or your system does not support it), then the import fails, and Python throws the Importerror exception we caught.

OK, we don't have termios, so let's try Msvcrt, which is a module unique to Windows that can provide an API for many useful functions in Microsoft Visual C + + running services. If the import fails, Python throws the Importerror exception we caught.

If the first two do not work, we try to import a function from Easydialogs, which is a module unique to Mac OS and provides a variety of pop-up dialogs. Once again, if the import fails, Python throws a Importerror exception that we caught.

None of these platform-specific modules are valid (possibly, because Python has been ported to many different platforms), so we need to go back to using a default password input function (which is defined elsewhere in the Getpass module). Notice what we do here: we assign the function Default_getpass 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 by binding getpass to the correct function to suit your platform. Then when you call the Getpass function, you actually call the platform-specific function, which is already set for you. You don't need to know or care what kind of platform your code is running on, and as long as you call Getpass, it's always handled correctly.

A try...except block can have an else clause, just like an if statement. If no exception is thrown in the try block, then the ELSE clause is executed. In this case, that means that if the from Easydialogs import Askpassword is working, we should bind the Getpass to the Askpassword function. Each other try...except block has a similar else clause and binds getpass to the appropriate function when we find that an import is available.

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

Python exception handling [go]

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.