except: #Catch all exceptions
except: <Exception name>: #Catch specified exception
except: <exception name 1, exception name 2): catch exception 1 or exception 2
except: <exception name>, <data>: capture the specified exception and its attached data
except: <exception name 1, exception name 2>: <data>: catch exception name 1 or exception name 2, and attached database
Common exception names:
Exception name Description
AttributeError exception raised by calling a method that does not exist
EOFError encountered an exception raised at the end of the file
ImportError
IndexError exception thrown out of bounds
IOError An exception caused by an I / O operation, such as an error when opening a file.
KeyError exception using a keyword that does not exist in the dictionary
NameError exception raised using a nonexistent variable name
TabError Exception Raised by Indentation Incorrectly
ValueError Exception raised by a value that does not exist in the search list
ZeroDivisionError exception raised by a divisor of zero
There are several ways to raise an exception using raise:
raise exception name
raise exception name, additional data
raise class name
assert simplifies the raise statement:
It should be noted that the assert statement is generally used to verify program conditions during development. The assert statement is valid only when the built-in _debug_ is True. When a Python script is compiled into a bytecode file with the -O option, the assert statement is removed.
But unlike the raise statement, the assert statement only raises an exception when the conditional test is false. The general form of the assert language is as follows:
assert <conditional test>, <exception additional data> #where exception additional data is optional
python programming_Python exception mechanism try: code segment except exception type, e: exception handling code segment, if you do not know the exception type, you can use try: code segment except Except, e: exception handling code segment; Except is a generic exception type
A Python exception instance
A simple exception example, opening a non-existent file and throwing an exception:
#! / usr / local / bin / python3.2
try:
f = open ("file-not-exists", "r")
except IOError, e:
print ("open exception:% s:% s \ n"% (e.errno, e.strerror))
Keywords related to Python exceptions:
Keywords keyword description
raise / throw exception
try / except to catch exceptions and handle them
pass ignore exception
as defines an exception instance (except IOError as e)
finally code executed whether or not an exception occurs
else If the statement in try does not raise an exception, execute the statement in else
except
In older versions of Python, the except statement is written as "except Exception, e". After Python 2.6, it should be written as "except Exception as e".
use
except
Without any exception type:
try:
do something
except:
handle except
All exceptions will be caught, including keyboard interrupts and program exit requests (you cannot exit the program with sys.exit () because the exception is caught), so use it with caution.
use
except Exception as e
You can catch all exceptions except those related to the program exiting sys.exit ().
else and finally
else means that if the code in try does not raise an exception, else will be executed:
try:
f = open ("foo", "r")
except IOError as e:
...
else:
data = f.read ()
Finally indicates that whether or not there is an exception, it will be executed:
try:
f = open ("foo", "r")
except IOError as e:
...
finally:
f.close ()
#! / 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 ability is very powerful, and it can accurately feedback error information to users. In Python, exceptions are also objects and can be manipulated. All exceptions are members of the base class Exception. All exceptions inherit from the base class Exception and are defined in the exceptions module. Python automatically places all exception names in the built-in namespace, so programs don't have to import the exceptions module to use exceptions. Once a SystemExit exception is thrown and not caught, program execution terminates. If an interactive session encounters an uncaught SystemExit exception, the session is terminated.
Method 1: try statement:
1Using try and except statements to catch exceptions
try:
block
except [exception, [data…]]:
block
try:
block
except [exception, [data ...]]:
block
else:
block
The rules of this exception handling syntax are:
· Execute the statement under try. If an exception is thrown, the execution process will jump to the first except statement.
· If the exception defined in the first except matches the thrown exception, the statement in that except is executed.
· If the exception thrown does not match the first except, the second except is searched, and there is no limit to the number of excepts that can be written.
· If all excepts do not match, the exception is passed to the next highest try code that calls this code.
· If no exception occurs, execute the else block code.
example:
try:
f = open ("file.txt", "r")
except IOError, e:
print e
The detailed cause of the caught IOError is placed in the object e and then the exception block of the exception is run
Catch all exceptions
try:
a = b
b = c
except Exception, ex:
print Exception, ":", ex
The thing to note when using the except clause is that when multiple except clauses catch exceptions, if there is an inheritance relationship between the exception classes, the subclass should be written first, otherwise the parent class will directly catch the subclass exception. Subclass exceptions placed behind will not be executed.
2 Use try and finally:
The syntax is as follows:
try:
block
finally:
block
The execution rules of this statement are:
· Execute the code under try.
· If an exception occurs, the code in finally is executed when the exception is passed to the next try.
· If no exception occurs, execute the code in finally.
The second try syntax is useful in cases where code is executed whether or not an exception occurs. For example, if we open a file in python for reading and writing, no matter whether there is an exception during the operation, I will eventually close the file.
These two forms conflict with each other, and the use of one kind does not allow the use of the other, and their functions are different.
2. Raise an exception manually using the raise statement:
raise [exception [, data]]
In Python, the simplest form to raise an exception is to enter the keyword raise followed by the name of the exception to be raised. Exception names identify specific classes: Python exceptions are objects of those classes. When a 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 the specified parameter (or a tuple of parameters).
example:
try:
raise MyError #throw an exception yourself
except MyError:
print ‘a error’
raise ValueError, ’invalid argument’
The captured content is:
type = VauleError
message = invalid argument
3. Use the traceback module to view the exception
When an exception occurs, Python "remembers" the exception that was thrown and the current state of the program. Python also maintains traceback objects, which contain information about the function call stack when an exception occurs. Remember that exceptions can be raised in a series of deeply 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 raised, 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 reaches the main program. This process of finding a suitable exception handler is called "Stack Unwinding." The interpreter, on the one hand, maintains information about the functions placed on the stack, and on the other hand, information about functions that have been "rolled out of the solution" from the stack.
format:
try:
block
except:
traceback.print_exc ()
Example: ... excpetion / traceback.py
4. Use the sys module to trace the last exception
import sys
try:
block
except:
info = sys.exc_info ()
print info [0], ":", info [1]
Or in the form:
import sys
tp, val, td = sys.exc_info ()
The return value of sys.exc_info () is a tuple, (type, value / message, traceback)
Type here ---- the type of the exception
value / message ---- exception information or parameters
traceback ---- An object containing call stack information.
It can be seen from this point that this method covers traceback.
5. Some other uses of exception handling
In addition to handling actual error conditions, there are many other uses for exceptions. A common usage in the standard Python library is to try to import a module and then check if it works. Importing a module that does not exist will raise an ImportError exception. You can use this approach to define multiple levels of functionality-depending on which module is valid at runtime or supporting multiple platforms (that is, 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 raise your exception using the raise command. If you are interested, please see the further reading section.
The following example demonstrates how to use exceptions to support platform-specific features. The code comes from the getpass module, a wrapper module that gets passwords from users. The implementation of obtaining a password is different on UNIX, Windows, and Mac OS platforms, but this code encapsulates all the differences.
Example supports platform-specific 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
termios is a module unique to UNIX that provides low-level 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 raises the ImportError exception we caught.
OK, we don't have termios, so let's try msvcrt, a module unique to Windows that provides an API for many useful functions in the Microsoft Visual C ++ runtime service. If the import fails, Python raises the ImportError exception we caught.
If the first two don't work, we try to import a function from EasyDialogs, which is a module unique to Mac OS that provides various types of popup dialogs. Once again, if the import fails, Python raises an 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 and use a default password entry function (this function is defined elsewhere in the getpass module). Note what we did here: we assigned the function default_getpass to the variable getpass. If you read the official getpass documentation, it will tell you that the getpass module defines a getpass function. It does this: adapt your platform by binding getpass to the correct function. Then when you call the getpass function, you are actually calling a platform-specific function, and this code is already set up for you. You don't need to know or care what platform your code is running on; just call getpass and it will always handle it correctly.
A try ... except block can have an else clause, just like an if statement. If no exception is raised in the try block, then the else clause is executed. In this case, it means that if from EasyDialogs import AskPassword import works, we should bind getpass to AskPassword function. Every other try ... except block has a similar else clause. When we find that an import is available, we bind getpass to the appropriate function.
Python-exception except statement usage and throwing exception