Python Error and exception summary __python

Source: Internet
Author: User
Tags assert integer division stdin

Mistakes happen almost every day in a programmer's life. In the past period, errors were either fatal to the program (and possibly the machine), or they produced a whole bunch of meaningless output that could not be identified by other computers or programs, and even the programmer could not understand its meaning. Once an error occurs, the program terminates execution until the error is corrected and the program is executed again. So, people need a "soft" way of dealing with the wrong, rather than terminating the program. At the same time, the program itself is evolving, not every error is fatal, even if the error occurs, the compiler or in the execution of the program can provide more useful diagnostic information, to help programmers solve the problem as soon as possible. However, errors are errors after all, and generally stop compiling or executing to solve them. A small piece of code can only let the program terminate execution, may also print out some vague hints. Of course, all of this was before the exception and exception handling occurred.

1. Error

In software terms, mistakes are grammatical or logical. Syntax errors indicate a structural error in the software that cannot be interpreted by the interpreter or the compiler cannot compile. These errors must be corrected before the program executes. When the syntax of the program is correct, the rest is logic error. Logical errors may be caused by incomplete or illegal input, and in other cases, logic cannot be generated, computed, or the process that the output requires cannot be performed. These errors are often referred to as domain errors and scope errors, respectively.

When Python detects an error, the interpreter indicates that the current stream is no longer performing, and then an exception occurs.

2. Abnormal

The best description of an exception is that it is an action taken outside the normal control flow because of an error in the program. This behavior is divided into two stages: the first is to cause errors to occur, and then to detect (and take possible measures) phase.

The first phase occurs after an exception condition (sometimes called an exception condition) occurs. The interpreter throws an exception whenever an error is detected and the exception condition is recognized. A throw can also be called a trigger or a build, through which the interpreter notifies the current control stream that an error occurred. Python also allows programmers to throw exceptions themselves, whether it's a Python interpreter or a programmer, an exception is a signal of an error, and the current stream will be interrupted to handle the error and take the appropriate action, which is the second phase.

The handling of exceptions occurs in the second phase. After an exception is raised, you can invoke many different actions, either by ignoring the error (logging the error without taking any action, by terminating the program after taking remedial action), or by trying to continue executing the program after mitigating the impact of the problem. All of these actions represent a continuation, or control, branch, and the key is that the programmer can instruct the program how to perform when the error occurs.

A language like Python that supports raising and handling exceptions (which is more important) allows developers to control them more directly when errors occur. Not only do programmers have the ability to detect errors, but they can also take more reliable remedial action when they occur. The robustness of the application has been greatly enhanced by the ability to manage errors at runtime.

Exceptions and exception handling are not new concepts. They also exist in Ada,modula-3,c++,eiffel, as well as in Java. The origin of the exception can be traced to operating system code that handles exceptions such as system errors and hardware interrupts. In about 1965 years, PL/1 as the first major language to support exceptions, and exception handling is the software tool it provides. Like other languages that support exception handling, Python uses the concept of "try/try" blocks and "catching/capture" blocks, and it is more "disciplined" with exception handling. Instead of blindly creating a "catch-all/capture all" code, we can create different processors for different exceptions.

3. Common exceptions in Python

nameerror: Trying to access an undeclared variable

>>> HP
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
nameerror : Name ' HP ' is not defined
>>> 

Nameerror that we have accessed a variable that has not been initialized. The symbol table in the Python interpreter did not find the other annoying variable. We'll talk about namespaces in the next two chapters, and now you can think of them as "address books" for connecting names and objects. Any variable that can be accessed must be listed in the namespace. The access variable needs to be searched by the interpreter, and if the requested name is not found in any namespace, a nameerror exception is generated.

zerodivisionerror: Divisor is zero

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Zerodivisionerror:integer division or modulo by zero

The examples we use are integers, but in fact, any number that is 0 apart will cause a zerodivisionerror exception.

syntaxerror: Python interpreter syntax error

>>> if
  File "<stdin>", line 1
    if
     ^
syntaxerror:invalid syntax

The SyntaxError exception is the only exception that does not occur at run time. It represents an incorrect structure in the Python code that the program cannot execute until it is corrected. These errors generally occur at compile time, and the Python interpreter is unable to convert your script into Python byte code. Of course this may also be when you import a defective module.

indexerror: Requested index exceeded sequence range

>>> alist = [' HP ']
>>> alist[1]
traceback (most recent call last):
  File "<stdin>", Line 1, at <module>
Indexerror:list index out of range

Indexerror is raised when you try to use a value index sequence that is out of range.

keyerror: Request a dictionary keyword that does not exist

>>> adict = {' HP ': ' Pavilion ', ' num ': 8888}
>>> print adict[' hp ']
traceback (most recent call Last):
  File "<stdin>", line 1, in <module>
keyerror: ' HP '

Mapping objects, such as dictionaries, rely on key words (keys) to access data values. A keyerror exception is thrown if the dictionary is requested using an incorrect or nonexistent key.

ioerror: input/Output error

>>> f = open ("HP")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ioerror: [Errno 2] No such file or directory: ' HP '

An operation such as attempting to open a nonexistent disk file can cause an operating system input/output (I/O) error. Any type of I/O error throws a ioerror exception.

Attributeerror: Attempting to access an unknown object property

>>> class MyClass (object):
...     Pass
... 
.. >>> myinst = MyClass ()
>>> myinst.hp = ' Pavilion '
>>> myinst.hp
' Pavilion '
>>> MYINST.HQ
Traceback (most recent):
  File "<stdin>", line 1, in <module>
attributeerror: ' MyClass ' OB Ject has no attribute ' HQ '

We store a value in MYINST.HP, which is the HP attribute of the instance myinst. Once the attribute is defined, we can access it using the familiar point/attribute operator, but if there is no attribute defined, such as our access to the HQ property, we will cause a attributeerror exception.

4. Detect and Handle Exceptions

Exceptions can be detected through a try statement. Any code in a try statement block is monitored to check for exceptions.

There are two main forms of try statements: try-except and try-finally . The two statements are mutually exclusive, which means you can only use one of them. A try statement can correspond to one or more except clauses, but can only correspond to a finally clause, or a try-except-finall Y compound statement.

You can use the try-except statement to detect and handle exceptions. You can also add an optional else clause to handle code that executes when no exception is detected. The try-finally only allows detection of exceptions and does some necessary cleanup (whether or not they occur) without any exception handling facilities. As you can imagine, compound statements are both possible.

try-except Statement

The most common try-except statement syntax is the following, consisting of a try block and except block (Try_suite and except_suite), or There is an optional reason for the error.

Try:
    try_suite      #watch for exceptions here to monitor the anomalies here
except exception[, reason]:
    except_suite   #exception-handling Code Exception handling codes
>>> try:
...     f = open (' HP ', ' r ')
... except IOError, E:
...     print ' could not open file: ', e
... 
Could not open file: [Errno 2] No such file or directory: ' HP '

Try statement with multiple except

The except statement in this format specifies an exception that detects a Exception name. You can connect multiple except statements together to handle a variety of exceptions that may occur in a try block, as follows:

Try:
    try_suite
except exception1[, Reason1]:
    suite_for_exception_exception1 except
, exception2[, Reason2]:
    suite_for_exception_exception2
>>> def safe_float (obj):
...     Try:
...             retval = float (obj) ...     Except ValueError: ...             retval = ' could not convert non-number to float '
...     Except TypeError: ...             retval = ' object type can ' is converted to float '
...     Return retval ... 

>>> safe_float (' hp ')
' could not convert non-number to float '

>>> safe_float ({' HP ': ' Pavilion '}]
' object type can not is converted to float '

>>> safe_float (')
200.0
> >> safe_float (200.0)

except statements that handle multiple exceptions

We can also handle multiple exceptions in a except clause only if they are placed in a tuple, as follows:

Try:
    try_suite
except (exc1[, exc2[, ...) EXCN]]) [, reason]:
    SUITE_FOR_EXCEPTIONS_EXC1_TO_EXCN
>>> def safe_float (obj):
...     Try:
...             retval = float (obj) ...     Except (ValueError, TypeError):
...             retval = ' argument must be a number or numberic string '
...     Return retval ... 

>>> safe_float ([])
' argument must be a number or numberic string '
>>> safe_float ("HP")
' argument must be a number or numberic string '
>>> safe_float ("123")
123.0
>>> Safe_float (123)
123.0

Note: The remaining statements after the exception occurrence point in the try statement block will never arrive (and therefore will never be executed). Once an exception is raised, you must decide where the control flow will next arrive. The remaining code will be ignored, the interpreter will search the processor, and once found, execute the code in the processor.

If the appropriate processor is not found, the exception is transferred up to the caller to process, meaning that the stack frame immediately returns to the previous one. If the processor is not found at the upper level, the exception continues to be transferred up until the appropriate processor is found. If the processor is still not found at the top level, the exception is considered unhandled, and the Python interpreter displays a trace return message and exits.

The try-except statement that Python provides to programmers is to better track potential bugs and prepare the logic to handle exceptions in code, a mechanism that is hard to implement in other languages, such as C. It is designed to reduce the number of errors in the program and to ensure that the program executes properly after an error. As a tool, only the right local use of it can make it work.

Avoid loading large chunks of code into try-except and then using pass to ignore errors, you can catch specific exceptions and ignore them, or catch all exceptions and take specific actions. Do not catch all exceptions, and then ignore them.

Exception Parameters

Exceptions can also have parameters, which are passed to the exception handler after the exception is raised. When an exception is raised, the parameter is passed as additional help information to the exception handler. Although the reason for the exception is optional, the standard built-in exception provides at least one parameter that indicates a string of reasons for the exception.

The parameters of the exception can be ignored in the processor, but Python provides the syntax to hold the value, and we've got a connection to it: To access the exception reason provided, you must keep a variable to hold the argument. Put this parameter after the except statement, followed by the exception to be processed.

This syntax for except statements can be extended to:

# Single Exception
except exception[, reason]:
    suite_for_exception_with_argument

# Multiple exceptions
except (Exception1, Exception2, ..., exceptionn) [, reason]:
    suite_for_exception1_ To_exceptionn_with_argument

Reason will be a class instance that contains diagnostic information from the code that caused the exception. The exception parameters themselves form a tuple and are stored as properties of the class instance (an instance of the exception class). In the first usage above, reason will be an instance of a Exception class.

>>> def safe_float (object):
...     Try:
...             retval = Float (object) ...     Except (ValueError, TypeError), Diag:
...             retval = str (diag) ...     Return retval ... 

>>> safe_float (' hp ')
' could not convert string to float:hp '
>>> safe_float ({})
' Float () argument must be a string or a number '

ELSE clause

We've seen the else statement segment fit with other Python statements, such as conditions and loops. As for the try-except statement segment, its functionality is not much different from any other else you have seen: executing the else clause when no exception is detected in the try range.

Before any code in the else scope runs, all the code in thetry scope must be completely successful (that is, no exception is thrown before the end).

Try:
    try_suite
except exception[, reason]:
    suite_for_exception_exception
Else:
    else_      The Suite # executes this statement when there is no exception
>>> def safe_float (object):
...     Try:
...             Float (object) ...     Except (ValueError, TypeError), Diag:
...             retval = str (diag) ...     else: ...             retval = Float (object) ...     Return retval ... 

>>> safe_float ("HP")
' could not convert string to float:hp '
>>> safe_float ({})
' Float () argument must be a string or a number '
>>> safe_float ("123")
123.0
>>> safe_ Float (123)
123.0

finally clause

The finally clause is a piece of code that is executed whether or not an exception occurs. You can use finally only with a try , or with try-except (else optional) , or you can use a separate try-finally .

Try:
    A
except myexception: 
    B
Else: 
    C
finally: 
    D

Of course, you can have more than one except clause at any rate, but at least one except statement, and else and finally are optional. A,b,c and D are programs (code blocks). Programs are executed in the order that they are expected. (Note: The possible order is a-c-d[normal] or a-b-d[exception]). A finally block is executed whether the exception occurs in A,b, and/or C.

Another way to use finally is finally to have a separate and try . The difference between this try-finally statement and the try-except is that it is not used to catch exceptions. Instead, it is often used to maintain consistent behavior regardless of whether an exception occurs or not. We were told thatfinally code snippets would be executed regardless of whether there was an exception trigger in a try .

Try:
    try_suite
finally:
    finally_suite      #无论如何都执行

try-except-else-finally Statement

Try:
    try_suite
except Exception1:
    suite_for_exception1
except (Exception2, Exception3, Exception4) :
    suite_for_exceptions_2_3_and_4
except Exception5, Argument5:
    suite_for_exception5_plus_argument
except (Exception6, Exception7), Argument67:
    suite_for_exceptions6_and_7_plus_argument except
:
    Suite_for_all_other_exceptions
Else:
    no_exceptions_detected_suite
finally:
    Always_execute_ Suite

Whatever syntax you choose, you must have at least one except clause, and else and finally are optional.

With statement

The WITH statement is designed to remove the related code from the try,except , and finally keywords and resource allocations from the flowchart, rather than as Try-except-finally just simplifies the code to make it easy to use. The basic usage of the WITH syntax looks as follows:

With context_expr [as Var]:
    with_suite
With open ('/etc/passwd ', ' R ') as F: for
    eachline in F:
        # ... do stuff with eachline or f ...

This code attempts to open a file and, if everything works, assigns the file object to F. Then, iterate through each row in the file with an iterator, and when it is done, close the file. Whenever an exception occurs at the beginning, middle, or end of this piece of code, the cleanup code is executed, and the file is still automatically closed.

5. Triggering an exception

Raise Statement

The raise statement supports a very flexible parameter that corresponds to a syntax that supports many different formats. Rasie General usage is:

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

The first argument, Someexcpetion, is the name that triggers the exception. If so, it must be a string, class, or instance (see below). If there are other parameters (ARG or traceback), you must supply the someexcpetion.

The second symbol is an optional args (for example, a parameter, value is passed to the exception. This can be a separate object or a tuple of an object. When an exception occurs, the parameters of the exception are always passed in as a tuple. If the args is originally a tuple, then pass it to the exception to deal with; if args is a separate object that generates a tuple of only one element (that is, a single element tuple). In most cases, a single string is used to indicate the cause of the error. If a tuple is passed, the usual composition is an error string, an error number, and possibly a wrong address, such as a file, and so on.

The last parameter, Traceback, is also optional (actually rarely used), and, if so, is when an exception triggers a newly generated trace (Traceback) object for exception-normalization (exception-normally). When you want to throw back an exception, The third parameter is useful (can be used to differentiate between previous and current locations). If you do not have this parameter, fill out none.

6. Assertion Statement

An assertion statement is equivalent to a Python expression that triggers a assertionerror (assertion error) exception if the assertion succeeds in not taking any action (like a statement). The syntax of the Assert is as follows:

Assert expression[, arguments]
>>> assert 1==1
>>> assert 1 = 1
>>> assert 2 + 2 = 2 * 2
>>> assert len ([' HP ', ' 5 ']) <
>>> assert range (3) = = [0, 1, 2]
>>> assert 1 = 0
traceback (most rec ENT call last):
  File "<stdin>", line 1, in <module>
assertionerror
>>> try:
...     Assert 1 = 0, ' One does not equal zero silly! '
... except Assertionerror, args:
...     Print '%s:%s '% (args.__class__.__name__, args)
... 
Assertionerror:one does not equal zero silly!

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.