Python Learning notes Summary (iv) exception handling

Source: Internet
Author: User
Tags define exception finally block

1. Basic
Try/except/else: "Else is optional" Catch the exception in the code and recover, match except inside the error, and execute the code defined in except, and then continue executing the program (after the exception is caught by except after the exception, will not interrupt the program, Continue executing the program following the try statement)
The code block underneath the try first line represents the main action of this statement: The program code that is trying to execute. The EXCEPT clause defines the exception handler that is thrown within the try code block, while the ELSE clause, if any, provides the processor to execute without exception.
Try/finally: Performs cleanup behavior regardless of whether an exception occurs (the program breaks the program when an exception occurs, but executes the finally code)
Raise: Manual contact in code is abnormal.
Assert: Conditionally triggering an exception in program code. Assert is almost always used to collect user-defined constraints
With/as implements the environment manager in Python2.6 and subsequent releases.
A user-defined exception is written as an instance of the class, not as a string.
Finally can appear in the same try statement as the except and else clauses,
You can mix except and finally clauses within the same try statement: Finally, the last execution, whether or not an exception is thrown, and no matter whether the exception is caught by the except clause. Finally there is no exception to execute
The except snaps to the corresponding exception before executing. Else no exception is executed,
That is, the EXCEPT clause captures any exception that occurs when the try code block executes, and the ELSE clause executes only if the try code executes without exception, and the finally clause cannot be released.
2, try statement clause form
Description of clause form
Except: Capturing all (other) exception types
Except name: Catch only specific exceptions
Except Name,value: Captures all exceptions and their additional data (or instances)
Except (name1,name2) to catch any listed exceptions
Except (name1,name2), value: Captures any listed exceptions and obtains their extra data
else: If no exception is thrown, run
Finally: This code block is always run, regardless of whether an exception occurred
An empty except clause captures any exception that is thrown while the program is executing without being caught. To get the actual exception that occurs, you can start from the built-in
SYS module takes out 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 class-based exceptions, these two elements correspond to the class of the exception and the instance of the thrown class, respectively.
The sys.exc_info result is a better way to get the most recently thrown exception. If no processor is being processed, a tuple containing three values of none is returned.
Otherwise, it will be returned (Type,value and Traceback)
*type is the exception type of the exception being handled (a class object based on the class exception)
*value is the exception parameter (its associated value or the second parameter of the raise, and if the exception type is a class object, it must be an instance of a class)
*traceback is a Traceback object that represents the stack that was called when the exception first occurred.
3. TRY/ELSE clause
Do not put the code in the else in try:. Make sure that the except processor executes only because the wrapper is actually failing the code in the try, not the failure of the condition in else.
Else clause to make the logical seal explicit
4. try/finally clause
Python first runs the code block under try:
If no exception occurs when the try code block runs, Python jumps to the finally block of code. Then the entire try statement continues to execute.
If the try code block runs out of exception, Python will return to run the finally block, but will then pass the exception up to the higher try statement or the top-level default processor. The program will not continue executing in the Try statement.
Uppercase (Open ('/etc/rc.conf '), output). Process ()
Open ('/etc/rc.conf '). Close
5. Unified try/except/finally Clause
Unified after version 2.5 (including version 2.5)
Except Exception1:
Except Exception2:
The Main-action code in this statement is executed first. If the program code (main-action) throws an exception, the except code block is tested individually, looking for statements that match the exception thrown. If an exception is thrown
The Exception1 executes the HANDER1 code block, and if the exception is thrown Exception2, the HANDER2 code block is executed. And so on If no exception is thrown, the Else-block code block is executed.
No matter what happens before, when the Main-action code block is complete. Finally-block will execute.
6. Merge except and finally by nesting
Except Exception1:
Except Exception2:
Same as the 5 effect
7. Raise statement
To deliberately trigger an exception, you can use the Raise statement. The raise statement consists of the Raise keyword followed by the exception name (optional) to be thrown, and an optional additional data item that can be passed along with the exception.
Raise <name>
Raise <name>,<data>
The second form passes additional data items along with the exception, in the raise statement, the data is listed after the exception name, and in the try statement, the data is obtained by introducing a receive
Its variables are implemented. For example, if try introduces a exceptname,x: statement, the variable X is assigned the additional data item listed in raise, if no default is defined by the
is the special object none. Once captured by any except clause in the program, the exception is dead (that is, it is not passed to another try), unless another raise statement or
caused by an error. Now the user-defined exception should be the class instance object.
8. Assert statement
Assert can conditionally trigger an exception in program code and can be considered a conditional raise.
Keep in mind that the assert is almost always used to collect user-defined constraints, rather than capturing inherent program design errors. Because Python automatically collects program design errors, it is often not necessary to write
Assert to catch things that are out of index value, type mismatch, and divisor 0.
The statement form:
Assert <test>,<data>
>>> def f (x):
... assert x>0, ' x must be great Zerot '
... return x**2

Second, the exception object
Python2.5 version string exceptions produce a ' deprecation ' (not recommended) ' warning. PYTHON3.0 will no longer support string exceptions, and the python2.7 version is no longer supported.
All exceptions are class-based exceptions, and string exceptions have exited the historical stage.
1. Class-based exceptions
Sys.exc_info () A common way to crawl recently occurring anomalies.
For class-based exceptions, the first element in the result is the exception class that is thrown, and the second is the actual instance thrown.
Note: The current Python documentation states that user-defined exceptions are best inherited from exception built-in exceptions (but not required)
In a try statement, capturing its superclass captures the class and all subclasses under the superclass in the class tree: The superclass becomes the name of the exception class, and the subclass becomes the specific
The exception type. Using the superclass of the exception, this class also captures the ability to add function exceptions (in subclasses) in the future without affecting the program.
Python2.5 later versions write each exception as a class (must), inheriting exception from the top of the exception tree (not required).
The basic principle is that in an exception handler, it is generally better to be more specific than normal.
2. Built-in exception class
Python organizes built-in exceptions into layers to support a variety of capture modes
Exception: Exception top-level root superclass
StandardError: Super class for all built-in error exceptions
Arithmeticerror: Superclass of all numeric errors
Overflowerror: A subclass that identifies a particular numeric error
Can be found in the Python library manual or in the help text of the EXCEPTIONSN module.
>>> Import Exceptions
>>> Help (Exceptions)
3. Define exception text
For class-based exceptions, the first element in the result is the exception class that is thrown, and the second is the actual instance thrown
>>> raise Mybad ():
>>> Raise Mybad ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
__main__. Mybad: <__main__. Mybad instance at 0x2850d26c>
This kind of display is unfriendly. Improved display, you can define a __repr__ or __str__ display string overload method in a class, which returns an exception to the desired default processor display string.
>>> class Mybad ():
... def __repr__ (self):
... return "Sorry--my mistake!"
>>> Raise Mybad ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
__main__. Mybad:sorry--my mistake
This changes the instance of the display class to the text we define.
Note: If you inherit from the built-in exception class, the error test will be slightly changed, and the constructor parameters are automatically stored and displayed in the message. "You can also put inherited overloads"
>>> class Mybad (Exception):p
... >>> raise Mybad ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
__main__. Mybad
>>> Raise Mybad (' The ', ' bright ', ' side ', ' of ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
__main__. Mybad: (' The ', ' bright ', ' side ', ' of ')
4. Sending additional data and instance behavior
The way to attach environment information to class-based exceptions is to fill in the instance's properties in the thrown instance object, usually in the constructor method of the class. In the exception handler, it is listed
To assign a variable to the instance being raised, then read the additional transpose information through the variable name and invoke any underlying class method. "Very powerful"
>>> class Formaterror:
... def __init__ (self,line,file):
... self.line=line
... self.file=file
>>> def parser ():
Raise Formaterror (42,file= ' diege.txt ') #手动定义异常, class-based exceptions, class constructors pass two of data.
>>> Try:
... parser ()
Except formaterror,x: A variable that passes over data #定义接受异常 (an instance of a class-an instance that is generated when an exception is thrown).
... print ' Error at ', X.file,x.line #显示实例传递过来的数据
Error at Diege.txt 42
5, the general form of raise
Raise string #基于字符串的异常, obsolete
Raise String,data #基于字符串的异常, obsolete
Raise instance #最常用的模式, directly followed by an example: Raise Formaterror (42,file= ' diege.txt ')
Raise Class,instance
To be compatible with older versions of strings for built-in exceptions, 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), equivalent to raise instance form
>>> def parse ():
... raise Formaterror, ("Diege.txt")

Third, the design of abnormal
1. Nested exception handler
To nest inside a try as a function
Nesting using syntax
2. Abnormal Custom Users
1) Exceptions are not always errors
3. Core language Summary
Generally, Python provides a hierarchical toolset.
Built-in Tools:
Such built-in types as strings, lists, and dictionaries can make programming faster.
Python extensions:
For more important tasks, you can write your own functions, modules, and classes to extend the Python
Compiled extensions:
Python's toolbox type.
Classification examples
Object Type list, dictionary, file, and string
function Len,range,apply,open
Exception Idexerror,keyerror
Module Os,tkinter,pickle,re
Property __dict__,__name__,__class__
External Tools Numpy,swig,jython,ironpython

Python Learning notes Summary (iv) 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: 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.