Python Learning (12) -- Exception Handling (3)

Source: Internet
Author: User

Exception Handling (3)

I. Exception Basics
Try/retry T: capture and recover exceptions in the code, match errors in wait t, and manually commit the code defined in T, and then continue to execute the program (when an exception occurs, after exceptions are caught by the retry t, the program will not be interrupted and the program following the try statement will continue to be executed)
Try/finally: Execute cleanup regardless of whether an exception occurs or not (when an exception occurs, the program will be interrupted, but the finally code will be executed)
Raise: a manual exception occurs in the code.
Assert: triggers exceptions in program code conditionally.
With/as implements the Environment Manager in python2.6 and later versions.
User-defined exceptions must be written as class instances, rather than strings ,.
Finally can appear in the same try statement as except T and else clauses,
1. Abnormal roles
Error Handling
Event Notification
Special case processing: sometimes it is rare to adjust the code for processing. The exception processor usually handles these rare cases, saving you the trouble of writing code for special situations.
Termination
Unconventional Control Process

>>> X = 'diege >>> def fetcher (OBJ, index ):... return OBJ [Index]... >>> fetcher (x, 4) 'E'> fetcher (x, 5) traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 2, in fetcherindexerror: String Index out of range >>> try :... fetcher (x, 5) # try to capture 5th characters... failed t indexerror: # If an exception occurs, [specify the name of the exception to be thrown ]... print fetcher (x,-1) # capture the last character... E >>> def catcher ():... try :... fetcher (x, 5 )... couldn t indexerror :... print fetcher (x,-1 )... print "continuing"... >>> catcher () econtinuing

We can see that the task is recovered from an exception and continues to be executed.
Try/finally: Execute cleanup regardless of whether an exception occurs or not (when an exception occurs, the program will also terminal, but will execute finally code)

>>> try:...     fetcher(x,4)... finally:...     print 'after fetch'...'e'after fetch

If no exception occurs, execute the code in the finally statement.
In case of exceptions

>>> try:...     fetcher(x,5)      ... finally:              ...     print 'after fetch'...after fetchTraceback (most recent call last):  File "<stdin>", line 2, in <module>  File "<stdin>", line 2, in fetcherIndexError: string index out of range

When an exception occurs, the finally statement code is also executed.
In actual application, try/try t combination can be used to capture exceptions and recover from them, while try/finally combination is very convenient to ensure that
If an exception occurs in the Code, the termination will certainly run. For example, try/try t to capture errors caused by code imported from a third-party library, and then try/finally to ensure
Close the file or terminate the server connection.
You can mix the begin T and finally clauses in the same try statement: Finally must be executed back, whether or not an exception is thrown or not, whether the exception is caught by the limit t clause
2. Try/try t/else statement
Complete try format: Try/multiple begin t/else statements
Else is optional
The code block under the first line of try represents the main action of this statement: the program code to be executed. The limit t clause defines the exception processor thrown in the try code block, while the else clause (if any) provides the processor to be executed when no exception occurs.
* If an exception occurs during the execution of the try code block statement, python will jump back to try and execute the statement below the first commit t clause that meets the exception. After the retry T code is executed (unless the retry T code block causes another exception), the entire try statement will be executed after the control is complete.
* If the exception occurs in the try code block and there is no matching limit t clause, the exception will be passed up to the program before entering try, or to the top layer of the process (use python to terminate the program and print the default error message)
* If no exception occurs in the statements executed under the first line of try, python will execute the statements in the else line (if any), and the control will continue under the entire try statement.
That is to say, the limit t clause captures all exceptions that occur when the try code block is executed, while the else clause is executed only when the try code is executed without exceptions, and the finally clause cannot be released.
3. Try statement clause form
Sentence format description
Except T: Catch all (other) exception types
Failed t name: only catch specific exceptions
Handle t name, value: capture all exceptions and its extra data (or instance)
Couldn t (name1, name2) Catch any listed exceptions
Except T (name1, name2), value: captures any listed exceptions and obtains additional data.
Else: If no exception is thrown, run
Finally: always runs this code block, whether or not exceptions occur
Handle T: Used in unexpected exceptions. Before handle T: You can define the exception that you can think of: handle T name1: handle T name2:
3. Try/else clause

        try:                customer=getargv[1]        except IndexError:                print "please give argv as customer!"        else:                scene=PizzaShop()                scene.order(customer)                print '...'

If you put the else: statement content in try:, it can also be executed. Simulate the else clause. However, this may cause incorrect exception categories. If "no exception occurs", this action is triggered.
Indexerror is regarded as a try code block failure. Therefore, the exception processor under try is incorrectly triggered. Change the else clause to clear the logic. Guaranteed memory T Processor
It is executed only because the code encapsulated in try fails, rather than because the behavior in else fails.
4. Try/finally Clause
Python first runs the try: code block below:
If no exception occurs when the try code block is running, Python jumps to the finally code block. Then the entire try statement is executed.
If an exception occurs when the try code block is running, python will still return to run the finally code block, but the exception will be passed up to a high Try statement or the top-level default processor. The program will not continue executing in the try statement.

        try:                Uppercase(open('/etc/rc.conf'),output).process()        finally:                open('/etc/rc.conf').close

5. Unified try/try t/finally clauses

try:    main-action:except Exception1:    hander1except Exception2:    hander2...else:    else-blockfinally:    finally-block

In this statement, the main-action code is executed first. If the program code (main-Action) causes an exception, the blocks of blocks will be tested one by one to find statements that match the thrown exception. If exception1 is thrown, hander1 code block is executed. If exception2 is thrown, hander2 code block is executed. And so on. If no
If an exception is thrown, The else-block code block is executed.
No matter what happens before, when the main-action code block is complete. All finally-blocks are executed.
6. Merge aggregate T and finally through nesting

try:    try:        main-action:    except Exception1:        hander1    except Exception2:        hander2    ...    else:        else-blockfinally:    finally-block

Same effect as 5
7. Raise statement
To deliberately trigger an exception, you can use the raise statement. The raise statement is composed of the raise keyword followed by the Exception name to be thrown (optional) and an optional additional data item, which can be passed along with the exception
Raise <Name>
Raise <Name>, <DATA>
Raise
Note: <Name> it must be pre-defined. Otherwise, it will cause an undefined error.
In the second form, when an exception is passed, the data in the raise statement is listed after the Exception name. In the try statement, the data is received by introducing
Its variables are implemented. For example, if you try to introduce an effectname, X: Statement, the variable X will be assigned an additional data item listed in raise. If no definition is defined, it will be accepted by default.
Is the special object none. Once caught by any limit t clause in the program, the exception will die (that is, it will not be passed to another try) unless it is captured by another raise statement or
Error. The user-defined exception should be a class instance object.
8. Assert statement
Assert can trigger exceptions in program code with conditions and can be considered as conditional raise.
Remember: assert is almost always used to collect user-defined constraints, rather than capturing internal program design errors. Because Python automatically collects program design errors, it is usually necessary to write assert to capture events that exceed the index value, Type mismatch, and division of 0.
The exception is assertionerror. If it is not captured by try, the program will be terminated.
Statement format:
Assert <Test>, <DATA>
Instance

>>> def f(x):...     assert x>0,'x must be great zerot'...     return x**2...>>> f(2)    4>>> f(-1)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 2, in fAssertionError: x must be great zerot

2. With/as Environment Management
Python2.6 introduces a new exception-related statement: With and its optional as clauses. This statement is designed to work with the Environment manager object (supporting the new method protocol.
In short, the with/as statement is designed as an alternative to common try/finally usage modes. Like try/finally statements, with/as statements are also used to define
Terminate or "Clean up", whether or not exceptions occur in the step. Unlike try/Finally, the with Statement supports richer object-based protocols and supports entry
And exit action.
Basic with statement format:
With expression [as variable]:
With Block
Expression returns an object to support the environment management protocol. If the as clause is used, this object can return a value and assign a value to the variable name variable.
Note: variable is not the result of assigning values to expressions. expression is an object that supports the environment protocol, while variable is the result of assigning values to other things (??)
Then, the object returned by expression can start the program on its own before it starts with-block. After the code block is completed, the program code is terminated, regardless of whether the code block causes an exception.
Some built-in Python objects have been reinforced and support the environment management protocol. Therefore, they can be used for with statements. For example, if the file object has an Environment Manager, it can be automatically closed after the with code block
File.
>>> With open ('/etc/rc. conf') as myfile:
... For line in myfile:
... Line = line. Upper ()
... Print line
Here, an open call will return a simple file object and assign it to the variable name myfile. We can use a general file tool to use myfile: In this case, the file iterator will
Read data row by row in the for loop.
This object also supports the environment protocol used by the with statement. After the with statement is executed. The Environment Management mechanism ensures that the object referenced by myfile is automatically closed. Instant Processing
This file causes an exception for the for loop.
The Environment Manager has an advanced write mechanism. It is not a formal component of Python. For a simple purpose, try/finally statements can provide sufficient support for terminating the activity.

Iii. Exception object
For class-based exceptions, you can create various exception classes with additional status information and support inheritance. Applicable class exceptions whenever possible. Class exceptions have the following features;
* Provides type classification to better support future changes: when a new exception is added in the future, you do not need to modify it in the try statement.
* It is the same as the reasonable location of the environment information stored in the try processor: in this case, you can have the status information and callable methods, and read the information through instances.
* Exceptions can be involved in the inheritance level to obtain common behaviors. For example, the inherited display method can provide a common error message appearance.
All built-in exceptions are organized into inheritance trees.
If the python2.5 string is abnormal, A 'describecation' (not recommended) 'warning is generated. Python3.0 no longer supports string exceptions.
1. String-based exceptions

>>> myexc="My exception string">>> try:...     raise myexc... except myexc:...     print "caught"...Traceback (most recent call last):  File "<stdin>", line 2, in <module>TypeError: exceptions must be old-style classes or derived from BaseException, not str

Python 2.7 is no longer supported
2. class-based exceptions

>>> Class General: Pass >>> class spec1 (General): Pass >>> class spec2 (General): Pass >>> def raiseer0 ():... X = General ()... raise x >>> def raiseer1 ():... X = spec1 ()... raise x >>> def raiseer2 ():... X = spec2 ()... raise x >>> for func in (raiseer0, raiseer1, raiseer2 ):... try :... func ()... using t General: # Use the abnormal super class General, so that the subclass can also capture the function exception (in the subclass) in the future, without affecting the program .... Import sys... print 'caught: ', sys. exc_info () [0]... caught :__ main __. generalcaught :__ main __. spec1caught :__ main __. spec2

In a try statement, capturing its superclass will capture this class, And all subclasses under the super classes in the class tree: The superclass will become the name of the exception category, the subclass will become a specific
Exception type.
In Versions later than python2.5, each exception is written as a class (required) and the exception (not required) is inherited from the top layer of the exception tree ).
SYS. exc_info () is a common method for capturing recent exceptions.
For a class-based exception, the first element in the result is the exception class, and the second is the actual instance.
Note: currently, the python instruction file indicates that the exception defined by the user is best inherited from the exception built-in exception (but not required ).
Class General (exception): Pass
For large and multi-level exceptions, using class capture classification in a sentence T clause is easier than listing each member in a category. Adds a subclass extension exception level ,. It will not damage
The first code.
If no class is used, excpet (General, spec1, spec2) will be used in excpet to capture the string class.
The basic principle is that exception processors are generally better than General processors.
3. built-in exception class
Python organizes built-in exceptions into layers to support various capture Modes
Exception: the top-level root class of the exception
Standarderror: superclasses with built-in error exceptions
Arithmeticerror: Super class with all numeric errors
Overflowerror: a subclass that identifies specific numeric errors.
You can refer to the python library manual or the help text of the exceptionsn module.
>>> Import exceptions
>>> Help (Exceptions)
Baseexception
Exception
Standarderror
Arithmeticerror
Floatingpointerror
Overflowerror
Zerodivisionerror
Assertionerror
4. Define abnormal text
For a class-based exception, the first element in the result is the exception class, and the second is the actual instance.
>>> Raise mybad ():
>>> Raise mybad ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
_ Main _. mybad: <__ main _. mybad instance at 0x2850d26c>
This display is unfriendly. Improved display: you can define _ repr _ or _ STR _ in the class to display the string overload method, so as to return an exception to the desired default processor to display the string.
>>> Class mybad ():
... Def _ repr _ (Self ):
... Return "sorry -- my mistake! "
...
>>> Raise mybad ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
_ Main _. mybad: Sorry -- my mistake
In this way, the display class instance is changed to the text we define.
Note: If you inherit from the built-in exception class, the error test will slightly change. The constructor parameters are automatically stored and displayed in the message. [Inheritance can also be overloaded]
>>> Class mybad (exception): Pass
...> Raise mybad ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
_ Main _. mybad
>>> Raise mybad ('the ', 'bright', 'day', 'of ')
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
_ Main _. mybad: (The ', 'bright', 'day', 'of ')
5. Send additional data and instance Behavior
The method to append environment information to a class-based exception is to fill in the instance attributes in the resulting instance object, usually in the class constructor method. In the exception processor, is to list
Assign a value to the variable of the triggered instance, and then use this variable name to read the additional conversion information and call any basic class method. [Very powerful function]

>>> Class formaterror :... def _ init _ (self, line, file ):... self. line = line... self. file = file >>> def Parser ():... raise formaterror(42,file='diege.txt ') # manually define an exception. Based on a class exception, the class constructor transmits two data types. Try :... parser ()... struct t formaterror, X: # defines the variables for receiving data from an exception (instance of the Class-instance generated when an exception is thrown .... Print 'error at', X. File, X. Line # display the data passed by the instance... error at diege.txt 42

The string format is [obsolete]
Raise formaterror, {'file': 'diege.txt ', 'line': 43}
Failed t formaterror, X:
Print 'error at', X ['file'], X ['line']
6. General Form of raise
Raise string # string-based exception, out of date
Raise string, data # string-based exception, obsolete
Raise instance # The most common mode, directly connected to an instance: Raise formaterror(42,file='diege.txt ')
Raise class, instance
Raise
To be compatible with the old version with built-in exceptions as strings, you can also
Raise class # Same as: Raise class ()
Raise class, Arg # Same as: Raise class (ARG)
Raise clase (arg1, arg2,...) # Same as: Raise class (arg1, arg2 ...)
These are equivalent to raise class (ARG) and are equivalent to raise instance
>>> Def parse ():
... Raise formaterror,(42,'diege.txt ')

Iv. Abnormal Design
1. nested exception Processor
Write internal try as a function to nest

>>> Def Action2 ():... print 1 + [] >>> def Action1 ():... try :... action2 ()... handle t typeerror :... print "inner try" >>> try :... action1 ()... handle t typeerror :... print "outer try "... inner try use syntax nesting >>> try :... try :... action2 ()... handle t typeerror :... print "inner try "... handle t typeerror :... print "outer try "... inner try

Nested finally statements are all started due to an exception.

>>> try:   ...     try:...             raise IndexError...     finally:            ...             print "diege"... finally:     ...     print "DIEGE"...diegeDIEGETraceback (most recent call last):  File "<stdin>", line 3, in <module>IndexError

2. Unusual users
1) exceptions are not always errors
In python, all errors are exceptions. But not all exceptions are errors.

>>> while 1:...     try:...             line=raw_input()...     except EOFError:...             break...     else:...             print "print ...process nex line here.."

Raw_input () triggers the built-in eoferror at the end of the file
2) function signal conditions and raise
User-defined exceptions can also cause non-errors.
It is used for any function that cannot return alert values to indicate success or failure.

class Failure(Exception):passdef searcher():    if ...success...;        return ...founditem...    else:        raise Failure()try:    item=searcher()except Failure:    ...report...else:    ...use item here...

The core of python is dynamic type and polymorphism. It is usually more inclined to send signals of such situations with exceptions, rather than warning return values.
3) debug outside try
An empty limit t clause captures exceptions that are not caught during execution of any program. To obtain the actual exception, you can
The SYS module retrieves the call result of the SYS. exc_info function. This returns a tuple, and the first two elements of the tuple automatically contain the name of the current exception,
And related additional data (if any ). For a class-based exception, the two elements correspond to the exception class and the instance that triggers the class respectively.
4) testing in the running process
5) about SYS. exc_info
SYS. exc_info is a better way to obtain the exception caused recently. If no processor is processing, a triple containing three none values is returned.
Otherwise, (type, value, and traceback) will be returned)
* Type is the exception type of the exception being processed (A Class Object Based on the class exception)
* Value is an exception parameter (its associated value or the second parameter of raise. If the exception type is a class object, it must be a class instance)
* Traceback is a traceback object that represents the stack called when an exception occurs.
2. skills related to exceptions
Generally speaking, Python exceptions are easy to use. The real technique behind exceptions is to determine whether the limit t clause should be specific or versatile, and how much code should be included in the try statement.
1) What should I pack?
How much code is included in the try statement.
Brief principles
* Operations that often fail should be encapsulated in try statements. For example, the operations connected to the system status (File opening, SOCKET call, etc.) are the main candidates for try.
* In this case, the previous rule has a special case: in a simple script, you want to terminate the program when such operations fail, rather than being captured or ignored. If it is a major error,
This is more appropriate. Python errors generate useful error information, which is usually the best expected result.
* Try/finally to terminate the action to ensure their execution. This statement can execute code, regardless of whether an exception occurs.
* Occasionally, the call to a large function is encapsulated in a single try statement, instead of letting the function itself scatter into several try statements. This will be more convenient. In this case, the exception in the function
It will be passed up to the try around the call, and you can also reduce the amount of code in the function.
2) Too many captures: Avoid null limit t statements
If an empty limit t statement is used, it may intercept the events expected by the try processor at a higher level in the exception nested structure. This type of code may capture unrelated system exceptions. If a memory error occurs
Program errors, iteration stops, and system releases all cause exceptions in Python. Exceptions here should not be intercepted.
3) too few captures: Use class-based classification
3. Core language summary
1) Python tool set
Generally, Python provides a hierarchical set of tools.
Built-in tools:
Built-in types such as strings, lists, and dictionaries make programming faster.
Python extension:
For more important tasks, you can write your own functions, modules, and classes to expand python.
Compiled extensions:
The Toolbox type of Python.
Classification example
Object Type list, Dictionary, file, and string
Function Len, range, apply, open
Idexerror, keyerror
Module OS, tkinter, pickle, re
Attribute _ dict __,__ name __,__ class __
External tools: numpy, swig, Jython, ironpython
2) open tools for large projects
Pydoc
Pychecker check
Pyunit Test
Doctest Test
IDE Gui
The Configuration tool profile is a standard block module that implements source code configuration tools for python.
Debugger: the source code debugger module, called PDB, is similar to the C command line Debugger GDB.

>>> Import PDB >>> PDB. run ("Main ()") # Run the code debugging command in interactive mode> <string> (1) <module> () (PDB) action1 <function Action1 at 0x28495bc4> (PDB) Action1 () Inner try

Release Selection: a common packaging tool for python programs. Py2exe, pyinstaller, and freeze can both package bytecode and Python virtual machines.
Optimization option: the psyco system provides a real-time compiler that can translate Python bytecode into binary codes.
Large and eye-catching tips
 

This article is from the "diege" blog, please be sure to keep this source http://ipseek.blog.51cto.com/1041109/802914

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.