To deliberately set off an exception, you can use the Raise statement in the following form:
Raise <name> #manually Trigger an exception
Raise<name>,<value> #pass extra data to catcher too
Raise #re-raise the most recent Excepti
The second form can pass additional data along with the exception, providing details for the processor.
Assert <test>,<data> #<data> is optional
If __debug__:
If not <test>:
Raise Assertionerror, <data>
Use With/as in 2.6 and later versions
with expression [as varible]:
With-block
Here expression returns an object that supports the environment Management protocol. If the AS clause is selected, this object can also return a value assigned to the variable name variable.
Note: variable is not the result of assignment to expression. And Varible is assigned to something else. Then, the object returned by expression can execute the launcher before With-block starts, and after that block of code is complete, the Abort program code is executed, regardless of whether the code throws an exception.
Wiht open (R ' C:\python\scripts ') as MyFile:
[Python]View Plaincopy
- For line in myfile:
- Print Line
- line = Line.repalce (' spam ',' spam ')
- ... More CODE here
How the With statement actually works:
1. To evaluate an expression, the resulting object is the environment manager, and he must have __enter__,__exit__ two methods.
2. The __enter__ method of the environment manager is called. If as exists, its return value is assigned to the variable following the AS, otherwise, it is discarded.
3. Nested code in the code block executes.
4. If the with code block throws an exception, the __exit__ (Type,value,traceback) method is called. These are also returned by Sys.exec_info with the same value. If this method returns False, the exception is raised again. Otherwise, the exception is aborted. Normally the exception should be re-thrown so that the word is passed out to the WITH statement.
5. If the with code block does not throw an exception, the __exit__ method is still called, and its type, value, and Traceback parameter are passed with none.
The With/as statement is designed so that the initiation and termination activities that must occur around the code block of the program are bound to occur. is similar to try/finally statements (whether or not an exception happens to be executed), but With/as has a richer object protocol that defines the actions to enter and leave.