One of "Python learning", Error and exception __python

Source: Internet
Author: User
Tags assert exception handling

Author: jofranks original works, reproduced please indicate the source. All rights reserved, infringement must investigate!

Source: Http://blog.csdn.net/jofranks


Exceptions, errors are written in the program is inevitable, as long as the people will make mistakes. Once the error occurs, our program stops executing and you must modify the program before it can function correctly.

An exception is an action taken outside the normal control stream because of an error in the program.  What is this act of taking? It is divided into two aspects, namely:"1" caused by abnormal errors. The interpreter throws (triggers/throws/generates) an exception whenever an error is detected and the exception condition is recognized.      Of course, we can also throw an exception ourselves. In general, the anomaly is the signal that the error occurs.

"2" detection.


Exceptions and errors exist not only in Python, but in languages like C, C + +, Objective-c, Java, and so on. They are all alike.

Python uses the concept of "try" blocks and "capture (catching)" blocks to be more "disciplined" in exception handling;


OK, let's take a look at the exceptions in Python.

1:nameerror: Trying to access an unnamed variable

2:zerodivisionerror: Divisor is 0

3:syntaxerror:python Interpreter Syntax error This exception is the only exception that is not occurring at run time.

4:indexerror: The requested error tone is out of sequence range

5:keyerror: Request a dictionary keyword that does not exist

6:ioerror: input/Output error

7:attributeerror: Attempting to access an unknown object property

first look at the Try statement: Try-except, try-finally.

You can only use one of these two statements, a try can only correspond to one or more except clauses, but only one finally clause, or a try-except-finally compound statement.

1, Try-except

Try:
     monitor the exceptions here
except exception[, reason]:
     exception handling code

We can also look at an example:

Try:
      a = 1/0
except Zerodivisionerror, E:
      print ' ERROR: ', E

When it executes, if there is no error in the code in the try block, then he ignores the part in the except. An exception executes the portion of the except.

In a try block, if an exception is found, the code from the beginning of the exception point will not be executed. After that, the interpreter will start looking for the processor, and if it finds it, it will transfer the exception to the previous layer, and if the previous layer is not found then it will continue to be submitted, knowing that the appropriate processor is found. If the end is not found, then the exception is not processed.


OK, let's take a look at a try block following multiple except forms.

Try:
      monitor the exceptions here
except exception1[, reason]:
      exception handling code
except exception2[, reason]:
      exception handling Code
......

The execution is the same, an exception occurs, and the interpreter will look for a matching exception in this string of processors.

We can also write this:

Try:
    .....
except (Exception1, Exception2) [, reason]:
    .....

In fact, except can handle arbitrary exceptions, but there is one condition: they are placed in a tuple:

Except (e1[, e2[, E3]]) [, reason]



It's worth saying that the null except clause is not advocated in Python, and if you want to catch all the exceptions, then we're going to use a class of the exception in Python, which is baseexception.

Except Baseexception, E:


All right, find the anomaly, if we don't have an exception detected in the try range. We all know If--else statement, here too, he can't find us also give him an else clause, let him go to execute.

Here, before the code in our ELSE clause executes, the code in our try scope must be completely successful.



2, try-finally statement

The finally clause is a code snippet that is executed regardless of whether an exception occurs or does not occur.

Try:
    A
except e:
    B
Else:
    C
finally:
    D
Let's look at the difference between try-finally and try-except, and their difference is to catch the anomaly. Finally code snippets are executed regardless of whether there is an exception trigger in the try.

Let's take a look at his execution: when the code in the try scope produces an exception, it jumps to the finally clause immediately after the code in the FINALLY clause executes and the code in the try continues.

The last thing to note is that the code in finally has thrown another exception or terminated due to return, break, continue syntax, and the original exception will be lost and cannot be raised again.


The exception we are learning now is caused by the interpreter, but we can also trigger the exception ourselves, which is the raise statement:

raise [Someexception [, Args [, Traceback]]]

Someexception is the name that triggers the exception, and he must be a string, class, or instance.

Args is optional, he can make a separate object, or it can be a tuple of an object.

Traceback He is also optional, when the exception triggers a newly generated trace record object for exception-normalization. This parameter is useful if you want to throw an exception again.


Assertion:

He is a sentence that must be equivalent to Boolean truth.

When an exception occurs, it means that the expression is false.

Assertions are implemented through ASSERT statements, which you can simply imagine as raise-if statements.

Assert expression[, arguments]

If the assertion succeeds, it will not do anything. If you fail, then you have to leave assertionerror abnormal.

Such as:

Assert 1 = 1
assert 2 + 2 = 2 * 2
Assert range (3) = = [0, 1, 2]

We can use try-except to catch exceptions, or we can provide an exception parameter to assert

Try:
    assert q = = 0, ' One does not equal zero silly! '
Except Assertionerror, args:
    print '%s:%s '% (args.__class__.__name__, args)

The output is: Assertionerror:one does not equal zero silly.


Finally, let's discuss why we should use exceptions:

Today, with the development of technology and society, the development of the Internet, software is not only for GUI users, the Web server will also become the main application software customers, for the server, the application can not just direct failure or crash, if so, then will cause users to browse the Web page return error, I believe that this is every internet company or personal webmaster do not want to see, but also users do not want to see.

There is also the programmer, when creating an application, you use a lot of resources, but users hit the keyboard interrupt, the application will not perform cleanup work, may result in data loss and other problems. And when it comes to writing code, the function must be rewritten to return a "special" value for the lucky mistake.

Exceptions can simplify our code, or we can check the entire system of error management.



------------2012/7/28

------------Jofranks in Nanchang


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.