Python exception handling and assertion

Source: Internet
Author: User
Tags stack trace try catch unsupported

http://blog.csdn.net/pipisorry/article/details/21841883

Assertion

An assertion is a sentence that must be equivalent to a Boolean truth; In addition, the occurrence of an exception means that the expression is false. These work similar to the Assert macros in the C language preprocessor, but in Python they are built at run time (in contrast to compile-time discrimination).
If you've just touched on the notion of assertion, it's no harm. Assertions can be simply imagined as raise-if statements (more accurately, raise-if-not statements). Tests an expression that, if the return value is FALSE, triggers an exception.

An assertion statement is equivalent to a Python expression that triggers an assertionerror (assertion error) exception if the assertion succeeds in taking no action (like a statement). The syntax for assert is as follows:
Assert expression[, arguments]

Example assert mode in ["Train", "eval", "inference"] if the input mode is not in it triggers an exception

[When to use assertions in Python]

Discussion on the necessity of exception handling

The most important problem is that you hide the bug in the development process, if you did not add this try ... Catch, I'm afraid you've already found this bug, because the program is not going to run.

[Performance impact of Try catch on Code run]

[You write the Try ... Is catch really necessary? ]

Exception handling

(including the difference between Py2 and PY3)

Basic format

Python 3
Try

...

Except Exception as E:
Print (e)

However LZ recommends the following format:

Traceback
Try:
...
except
:
Print (Traceback.format_exc ())
Input ("Hold on ...")

Directly calling print Exception, e results in only one line of information, just the name and description of the exception. This allows you to output stack information, which can be clicked in the IDE to get to the wrong location and not be flashed.

Abnormal

1) So the exception is inherited from Baseexception, and the Stardarderror is removed. StandardErrorexception: In Python 2, StandardError is the StopIteration GeneratorExit KeyboardInterrupt SystemExit base class for all other built-in exceptions, except,. In Python 3, it StandardError has been canceled; Exception

Notes Python 2 Python 3
x =StandardError() x =Exception()
x =StandardError(a, b, c) x =Exception(a, b, c)

2) removed the sequence behavior of the exception class and the. Message property

3) exception chain, because __CONTEXT__ is not implemented in the 3.0A1 version

    1. Python 3 uses a new keyword relative to Python 2, which adds a comma after the exception type as .
    2. Keywords as can also be used in cases where multiple types of exceptions are captured at once.
    3. If you catch an exception, but don't care about accessing the exception object itself, the syntax for Python 2 and Python 3 is the same.
    4. Similarly, if you use an insurance method (fallback) to catch all exceptions, the syntax for Python 2 and Python 3 is the same.

You should never use this method (refer to the above fallback) when importing modules (or most other cases). Otherwise, the program may catch KeyboardInterrupt exceptions such as (if the user presses Ctrl-C to interrupt the program), making debugging more difficult.

Trigger Exception-raise Statement

In Python 3, there is a slight change in the syntax for throwing a custom exception.

Notes Python 2 Python 3
raise MyException Unchanged
raise  Myexception, ' error message ' raise  myexception ( ' error message '
raise MyException,‘error message‘, a_traceback raise MyException(‘error message‘).with_traceback(a_traceback)
raise ‘error message‘ Unsupported

Note:

    1. Throws an exception with no user-defined error message, in the simplest form, the syntax does not change.
    2. When you want to throw an exception with user-defined error messages, the change is obvious. Python 2 separates the exception class from the error message with a comma, and Python 3 passes the error message as an argument to the exception class. Python 2 supports both the old and the new exception triggering syntax, while Python 3 accepts only the parentheses syntax (which would otherwise trigger syntaxerror)
    3. Python 2 supports a more complex syntax to throw an exception with a user-defined backtracking (stack trace, heap trace). You can do this in Python 3, but the syntax is completely different.
    4. In Python 2, you can throw an exception with no exception class, just one exception message. In Python 3, this form is no longer supported. 2to3will warn you that it cannot automatically fix this syntax.
Throwing exceptions using lambda anonymous functions

How can I write a lambda expression that's equivalent to:
def x ():
Raise Exception ()
The following is not allowed:
y = lambda:raise Exception ()

Lambda Errmsg:exec (' Raise (Exception (errmsg)) ')

[Define a lambda expression that raises an Exception]

The throw method of the generator

In Python 2, the generator has a throw() method. The call a_generator.throw() throws an exception when the generator is paused, and then returns the next value obtained by the generator function. In Python 3, this functionality is still available, but the syntax is a little different.

Notes Python 2 Python 3
a_generator.throw(MyException) No change
Ii a_generator.throw(MyException,‘error message‘) a_generator.throw(MyException(‘error message‘))
a_generator.throw(‘error message‘) Unsupported
    1. In its simplest form, the generator throws an exception with no user-defined error message. In this case, there is no change in syntax from Python 2 to Python 3.
    2. If the generator throws an exception with a user-defined error message, you need to pass the error message string (Error string) to the exception class to instantiate it.
    3. Python 2 also supports throwing exceptions with only exception information. Python 3 does not support this syntax and 2to3 will display a warning message telling you that you need to fix this code manually.
Exception handling

The exception handling in Python 3 also changed a little. The "as" keyword must be used in Python 3.

Python 2

Try
Let_us_cause_a_nameerror
Except Nameerror, err:
Print err, '--and our error message '

Name ' Let_us_cause_a_nameerror ' is not defined--and our error message

Python 3
Try
Let_us_cause_a_nameerror
Except Nameerror as err:
Print (Err, '--and our error message ')

Name ' Let_us_cause_a_nameerror ' is not defined--and our error message

An example of except:

Consider the following file

Import sysbar(i):    Raise Keyerror (1)badtry:bar (int (sys.argv[ase:print (' key error ') print (e) bad ()       

Everything works fine in the Python2.

1key Error1

But things got a mess in Python3.

1key Errortraceback (most recent): In  <module> Bad    ()  ' e ' referenced Before assignment 

Note: The problem is that in Python3, the exception object cannot be accessed outside the exception block. (The reason is that a reference cycle is saved in the memory stack frame before the garbage collector runs and cleans the reference from memory)

One way to resolve this problem is to enclose a reference to an exception object in the exception block's domain to make it accessible. Here is the precedent for using a version of this technique that makes the code friendly to both Python2 and Python3:

Import sysbar(i):    Raise Keyerror (1)goodtry:bar (int (sys.argv[ase: Exception = e print (' key error ') print (Exception)       
Except for 0 exception Zerodivisionerror

Now divided by the variable a=0 will not be captured by try-except, and will be warned directly at runtime:

Runtimewarning:divide by zero encountered in Double_scalars

Only the direct divide by 0 will be captured by Try-except.

Other exceptions

X, Y is a dictionary that throws an TypeError exception if it cannot be compared with the × < Y. The 2.x version returns a pseudo-random boolean value.

Sys.exc_type, Sys.exc_value, Sys.exc_traceback

When handling exceptions, there are three variables that you can access in the SYS module: sys.exc_type,sys.exc_value,sys.exc_traceback. (In fact, these are in the time of Python 1.) Starting with Python 1.5, because of the new sys.exc_info, it is no longer recommended to use these three variables, which is a tuple containing all of the above three elements. In Python 3, these three variables finally no longer exist, which means that you have to use Sys.exc_info.

Notes Python 2 Python 3
Sys.exc_type Sys.exc_info () [0]
Sys.exc_value Sys.exc_info () [1]
Sys.exc_traceback Sys.exc_info () [2]

Phi Blog

Related to exception handling

[Python context manager contextlib and with statements]

Else mates with try except error control using

In an exception-handling statement, the ELSE statement block is executed when the try code block does not throw any exceptions.
def my_to_int (Str_param):
Try
print int (str_param)
Except ValueError:
print ' cannot convert {} to a integer '. Format (Str_param)
Else
print ' Convert {} to integer successfully '. Format (Str_param)
My_to_int ("123")
My_to_int ("me123")
Convert 123 to Integer successfully
Cannot convert me123 to a integer

As shown in the print log, the logic in the ELSE statement will be executed when the conversion succeeds without error, although this example may not have much practical use, but it can roughly illustrate the usefulness of else in fault handling: simplifying logic, Avoid using some of the flag values to be able to accurately grasp whether the error occurred to do some practical operation (such as when the data is saved if an error occurs, in the ELSE statement block rollback operation, and then can be followed by a finally statement to complete some cleanup operations.

Great Exceptations

Exceptions, as a control structure, is very common when working with databases, sockets, files, or any resource that might fail. Writing database operations using standard try, except structures is usually a way of typing.
Try
# Get API Data
data = Db.find (id= ' foo ') # may raise exception
# Manipulate the data
Db.add (data)
# Save it Again
Db.commit () # may raise exception
Except Exception:
# Log the failure
Db.rollback ()

Db.close ()
Can you find the problem here? There are two possible exceptions that will trigger the same except module. This means that finding data failure (or failing to establish a connection to the query data) causes a fallback operation. This is definitely not what we want, because at this point in time the transaction does not begin. The same fallback should not be the correct response to the database connection failure, so let's deal with different situations separately.


First, we will process the query data.
Try
# Get API Data
data = Db.find (id= ' foo ') # may raise exception
Except Exception:
# Log the failure and bail out
Log.warn ("Could not retrieve FOO")
Return


# Manipulate the data
Db.add (data)
Data retrieval now has its own try-except so that when we don't get the data, we can take any approach. Without the data our code is unlikely to do anything useful anymore, so we'll just exit the function. In addition to exiting you can also construct a default object, retrieve it again, or end the entire program.
Now let's wrap up the commit code separately so that it can be more elegant and error-handling.
Try
Db.commit () # may raise exception
Except Exception:
Log.warn ("Failure committing transaction, rolling back")
Db.rollback ()
Else
Log.info ("Saved The New FOO")
Finally
Db.close ()
In fact, we've added both ends of the code. First, let's look at the else, which executes the code here when no exception occurs. In our case, this is just a matter of writing the information about the success of the transaction to the log, but you can do more interesting things as needed. One possible application is to start a background task or notification.
It is clear that the function of the finally clause here is to ensure that db.close () is always able to run. Looking back, we can see that all the code related to data storage eventually forms a pretty logical grouping at the same indentation level. When code maintenance is required later, it is straightforward to see that these lines of code are used to complete the commit operation.

Phi Blog

Appendix

Common Python exception types

[Python exception programming Tips]

from:http://blog.csdn.net/pipisorry/article/details/21841883

(a) Python exception handling and assertion

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: 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.