To start on purpose , have access to raise sentence , Form the following :

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 , To provide details for the processor .

assert <test>,<data>  #<data> Optional.

if __debug__:

if not <test>:

raise AssertionError, <data>

stay 2.6 And later versions with/as

with expression [as varible]:

with-block

ad locum expression It returns an object , To support environmental management agreement . If you choose as Clause , This object can also return a value , Assign to variable name variable.

Be careful :variable Not assigned to expression Result . and varible It's assigned to something else . then ,expression The returned object can be found in with-block Prior to the start , Start the startup program first , And after the code block is complete , Execution abort program code , Whether or not the code throws an exception .

wiht open(r'C:\python\scripts') as myfile:

  1. for line in myfile:
  2. print line
  3. line = line.repalce('spam','SPAM')
  4. ...MORE CODE HERE

with How statements actually work :

1. Calculation expression , The resulting object is the environment manager , He has to have __enter__,__exit__ Two methods .

2. Environment manager's __enter__ Method will be called . If as There is , Its return value is assigned to as The latter variable , otherwise , To be discarded .

3. The code nested in the code block executes .

4. If with Code blocks throw exceptions ,__exit__(type,value,traceback) Method will be called . These are also caused by
sys.exec_info Return the same value . If this method returns false , The exception is raised again . otherwise , The exception will abort . Normally, an exception should be raised again , That's how it goes to
with Out of statement .

5. If with The code block did not throw an exception ,__exit__ Method will still call , Its type、value as well as traceback Parameters will be None Pass on .

with/as Sentence design , It's to make sure that the start and stop activities that have to happen around the program code block will happen . and try/finally sentence ( Whether an exception occurs or not, its leave action is executed ) similar , however with/as There are richer object protocols , You can define the actions of entering and leaving .

python And raise、assert、with/as More articles on Environment Manager

  1. python- modular , abnormal , Environment manager

    modular Module What is a module : 1. A module is one that contains a series of data , function , Class, etc 2. A module is a file , The module file name is usually .py ending effect : 1. Let's get some relevant data , function , Classes are logically organized together , Causative logic ...

  2. 【Todo】Python Interview question analysis record ( Modifiers, etc )

    First , Look at this code : class A(object): x = 1 gen = (lambda t: (t for _ in xrange(10)))(x) if __name__ == '__mai ...

  3. Python Instant web crawler project : Definition of content extractor (Python2.7 edition )

    1. Project background stay Python In the instant crawler project launch notes, we discuss a number : Programmers waste too much time debugging content extraction rules ( See above ), So we started this project , Free programmers from tedious debugging rules , Invest in higher end ...

  4. Python The name space of 、 Closure 、 Decorator

    One . Namespace 1. Namespace A namespace is a dictionary ,key Is a variable name. ( Include function . modular . Variable etc. ),value Is the value of the variable . 2. The type of namespace and the order of lookup - Local namespace : The current function - Global namespace : The current model ...

  5. python in raise Usage of

    About python in raise Shows the method that raises the exception : When the program goes wrong ,python An exception is automatically triggered , It can also be done through raise Show throw exception Once implemented raise sentence ,raise Subsequent statements are not executed If you do try ...

  6. Python Basics ( 7、 ... and ) python Three ornaments that come with me

    When it comes to decorators , I have to say python Three ornaments that come with me : 1.@property   Put a function , Use as an attribute @property modification , It's the method , Become an attribute to use . class A(): @prope ...

  7. Python Object oriented : Closures and decorators

    One . Closure 1. If a function is defined within the scope of another function , And references variables of outer functions , Then the function is called a closure . def outter(): name='python' def inner(): print na ...

  8. Python Rookie's Road :Python Basics - It's a powerful tool to push the grid up : Decorator Decorator

    One . Decorator Decorator is a very famous design pattern , Often used in scenarios with faceted requirements , The classic one is insert log . Performance testing . Transactions, etc . Decorators are an excellent design for this type of problem , We have decorators , We can extract a large number of functions from the function itself ...

  9. Python Advanced ( 7、 ... and )---- Parameter decorator , Multiple decorators decorate the same function and recursive simple case ( Fibonacci sequence )

    Python Advanced ( 7、 ... and )---- Parameter decorator , Multiple decorators decorate the same function and recursive simple case ( Fibonacci sequence ) A decorative device with parameters def wrapper_out(pt): def wrapper(func): ...

Random recommendation

  1. Javascript The difference between two equal signs and three equal signs in (==/===)

    ==// Represents a comparison of values ===// Represents a comparison of object types 1. about string,number Equal foundation type ,== and === There is a difference . a) Comparison between different types ,== Comparison “ Values converted to the same type ” see “ value ” Whether it is equal or not ,== ...

  2. Mysql binlog

    understand Mysql binlog Three modes of logging   In this article ,mysql in binlog Three modes of logging , Understand the differences between the various models , In order to make better use of . Friends in need suggest reference .   One , Pattern 1 Row Lev ...

  3. To configure DB2 The database of ODBC Connect

    open cmd window , Input db2cmd start-up db2 clp window Input db2 list node directory Check whether there are nodes that need to be connected to the database If it doesn't exist , be Node catalog :db2 catalog tcpip ...

  4. Introducing the Blog Module

    Introducing the Blog Module Now that we know about the basics of the zend-mvc skeleton application, ...

  5. Reprint ——Struts2 Medium constant Detailed explanation

    http://bhw1015.iteye.com/blog/1258441 By configuring these properties , You can change Struts 2 Some of the default behaviors of the framework , These configurations can be used in struts.xml Done in file , It can also be in s ...

  6. 【Linux】MySQL Decompressed version installation and allow remote access

    Installation environment / Tools 1.Linux( centOS edition ) 2.mysql-5.6.31-linux-glibc2.5-x86_64.tar Installation steps 1. download mysql Decompression version (mysql-5.6.31-l ...

  7. akka tips

    1.actorSelection, When it comes to actor In remote communication , have access to actorSelection. context.actorSelection("akka.tcp://app@other ...

  8. chown Detailed command

    chown effect : Change the owner and group of a file or directory , This command can be authorized to a user , Make the user program to specify the owner of the file or change the group to which the file belongs , Users can be users or users ID, User groups can be group names or groups ID,   ...

  9. avoid jquery Of click Multiple binding methods

    $("#xxx").click(function(){}) This will only be in the original click Method to continue adding new methods : The solution, of course, is to untie : $("#xxx").unbin ...

  10. 41)django-admin

    One : Introduce adopt django admin Can quickly generate background management functions . Two : Set up Under the same name of the project settings.py 1) stay INSTALLED_APPS add django.contrib.admin 2) stay I ...