Python BASICS (11): errors and exceptions, 2015 python

Source: Internet
Author: User
Tags integer division

Python BASICS (11): errors and exceptions, 2015 python

During the execution of the program, exceptions may occur, and errors may be fatal in the previous period. Later, with the development of the program, the handling methods of some errors will be gentle, when an error occurs, some diagnostic information and fuzzy prompts are generated. Help us handle exceptions.
I will learn Python exceptions today.

A program may have syntax or logic errors. A syntax error may cause the interpreter or compiler to be unable to work. Then, the program can run in ucoins.
When the syntax is correct, there is only a logic problem. There are two logical problems: incomplete or invalid input. The other is that the logic cannot be generated, computed, or executed. These errors are also called domain errors and range errors.
When Python detects an error, an exception occurs.

The exception is caused by a program error that occurs outside of normal control theory. This action has two phases:
1. Error phase caused by exceptions
2. Detection (and taking possible measures) phase
The first phase is to detect the error and realize the exception conditions. Then the interpreter will throw an exception and interrupt the current stream. Of course, Python allows programmers to raise exceptions themselves.
The second stage is to handle exceptions, ignore errors (record errors but take no action, take remedial measures and terminate the procedures), or try to continue executing the procedures after mitigating the impact of the problem.
Languages similar to Python that support exception triggering and handling allow developers to control errors more directly. This will greatly improve the robustness of the program.

Exceptions in Python
When the program crashes or ends due to an error, the "trackback/Trace return" message is displayed, containing information provided by the interpreter, including the name, cause, and row number of the error.
There are the following exceptions:

NameError: access an unstated variable >>> fooTraceback (innermost last): File "<stdin>", line 1, in? NameError: name 'foo' is not defined

This is a variable that has not been initialized. The access variable is searched by the interpreter. If the request name is not found in any namespace, A NameError is generated.

ZeroDivisionError: divisor 0 >>> 1/0 Traceback (innermost last): File "<stdin>", line 1, in? ZeroDivisionError: integer division or modulo by zero

Zero division of any value will cause ZeroDivisionError.

SyntaxError: Python interpreter syntax error >>> forFile "<string>", line 1for ^ SyntaxError: invalid syntax

SyntaxError is the only exception that occurs when it is no longer running. The program cannot be executed until it is corrected.

IndexError: the requested index is out of the serial range >>> aList = [] >>> aList [0] Traceback (innermost last): File "<stdin>", line 1, in? IndexError: list index out of range

IndexError is triggered when you try to use a value index sequence out of the range.

KeyError: request a dictionary keyword that does not exist >>> aDict = {'host': 'global', 'Port ': 80 }>>> print aDict ['server'] Traceback (innermost last): File "<stdin>", line 1, in? KeyError: server

When an incorrect key is used to request a dictionary, a KeyError exception is thrown.

IOError: Input/Output Error >>> f = open ("blah") Traceback (innermost last): File "<stdin>", line 1, in? IOError: [Errno 2] No such file or directory: 'blackh'

An operation similar to opening a non-existing disk file will cause an I/O error in the operating system. Any type of I/O error will cause an IOError.

AttributeError: Access unknown object attributes >>> class myClass (object ):... pass...> myInst = myClass () >>> myInst. bar = 'spam' >>> myInst. bar 'spam'> myInst. fooTraceback (innermost last): File "<stdin>", line 1, in? AttributeError: foo

In myInst. bar stores a value, that is, the bar attribute of the Instance myInst. after an attribute is defined, we can use the familiar vertex/attribute operator to access it. However, if no attribute is defined, for example, if we access the foo attribute, an AttributeError occurs.

Detect and handle exceptions
Python exception detection and processing has special syntax
The try statement is used to detect exceptions. Any code in the try statement block is detected to check whether exceptions occur.
The try statement has two main forms: try-try t and try-finally. These two statements are mutually exclusive and can only be used. A try statement corresponds to one or more limit t clauses, but can only correspond to one finally clause or a try-try t-finally compound statement.
Try-try t statement to detect and handle exceptions. You can add an optional else clause to process the code executed when no exceptions are detected. Try-finally only allows detection of exceptions and makes some necessary clear work, without any exception handling measures. The compound statement can be used for both.

The try-retry t statement syntax is as follows:

Try: try_suite # monitor the Exception token t Exception [, reason]: except_suite # Exception Handling Code

Here is an example:

>>> try:  f = open('try', 'r')except IOError, e:  print 'could not open file:', ecould not open file: [Errno 2] No such file or directory: 'try'

In this example, only the IOError exception is caught, and no other exception is captured by the processor.

Core notes: Ignore code, continue execution, and hand over
When an exception occurs in the try statement block, the remaining statements will never arrive. Once an exception is thrown, the next step of the control flow must be determined. The remaining code will be ignored, and the interpreter will search for the processor. Once found, the code in the processor will be executed.
If no proper processor is found, the exception is handed over to the caller for processing, which means that the stack framework immediately returns to the previous one. If no processor is found in the upper-layer caller, the exception will be handed over until a proper processor is found. If no processor is found at the top-layer, the exception is not handled. The Python interpreter displays the trace return message and exits.

Securely call built-in functions
In the following example, we will see the error when the value of float () is incorrect, and then encapsulate a safe function with try-example t:

>>> float('abc')Traceback (most recent call last):File "<pyshell#5>", line 1, in <module>float('abc')ValueError: could not convert string to float: abc>>> float(['this is', 1, 'list'])Traceback (most recent call last):File "<pyshell#6>", line 1, in <module>float(['this is', 1, 'list'])TypeError: float() argument must be a string or a number>>> def safe_float(obj):  try:    retval = float(obj)  except ValueError:    retval = 'could not convert non-number to float'  except TypeError:    retval = 'object type cannot be converted to float'  return retval>>> safe_float('xyz')'could not convert non-number to float'>>> safe_float(['this is', 1, 'list'])'object type cannot be converted to float'
The processing of multiple distinct T clauses is used here. The syntax is as follows:
except Exception1[, reason1]:  suite_for_exception_Exception1except Exception2[, reason2]:  suite_for_exception_Exception2 ...



You can also handle multiple exceptions in a distinct T clause, which requires exceptions to be placed in a single tuple:

except (Exception1, Exception2)[, reason]:  suite_for_Exception1_and_Exception2

To change the above function in this way, you can write it as follows:

def safe_float(obj):  try:    retval = float(obj)  except (ValueError, TypeError):    retval = 'argument must be a number or numeric string'  return retval

The distinct T statement can handle any number of exceptions, provided that it is placed in a single tuple, as shown below:

except (Exc1,...ExcN)[, reason]:  suite_for_exceptions_Exc1_to_ExcN

But what if we want to catch all exceptions?
You can write it as follows:

Try:... failed t Exception, e:... # An Exception occurred. The Exception type is stored in e.

Another less recommended method is to use the bare limit t clause:

try:  ...except:  ...

Although most exceptions are caught in the following method of the bare distinct T clause, you do not know the main cause of the exception. This method is not recommended because it cannot be avoided. This method may be canceled later.
For capturing all exceptions, some exceptions are not caused by error conditions. They are SystemExit and KeyboardInterrupt.
SystemExit is because the current Python application needs to exit, KeyboardInterupt indicates that the user has pressed the CTRL-C (^ C) and wants to close Python. If necessary, these exceptions will be caught by exception handling.
After Python2.5, the Exception is migrated, and a BaseException is enabled as the mother of all exceptions. KeyboardInterrupt and SystemExit are removed from the Exception, which is the same as the Exception:

|-(All other current built-in exceptions)


Core style: do not handle and ignore all errors
Python provides the try-retry t statement to better track potential errors and prepare the exception handling logic in the code. It is designed to reduce the number of program errors and ensure that the program runs normally after an error occurs.
If we have always filtered out any fatal errors with a general counter T, ignore them. For example, use the bare snapshot t statement.
We know that errors cannot be avoided. try-try t is used to provide a mechanism that can prompt errors or handle errors, rather than an error filter. It makes no sense to filter out any fatal errors.

Exception Parameter
An exception can also have a parameter. When an exception is thrown, it is passed to the exception processor. When an exception is thrown, the parameter is passed as an additional help message to the exception processor. Although the cause of the exception is optional, the standard built-in exception provides at least one parameter to indicate the cause of the exception.
An exception parameter needs a variable to be saved. It is placed after the handle T and followed by the exception to be processed. That is, the e variable I used in the above example.
In a single exception statement:

except Exception[, reason]:  suite_for_Exception_with_Argumentexcept (Exception1, Exception2, ..., ExceptionN)[, reason]:  suite_for_Exception1_to_ExceptionN_with_Argument

This reason will be a class instance containing diagnostic information from codes that cause exceptions. The exception parameter itself forms a tuple and is stored as an attribute of a class instance. In the above usage, reason will be an Exception class instance.
Most built-in exceptions are derived from StandardError. This tuples only contain a string indicating the cause of the Error. Generally, the name is a satisfactory clue.
Some third parties or other external libraries do not follow this standard agreement.

Core style: follows exception parameter specifications
When a built-in (built-in) exception is thrown in your code, follow the rules as much as possible, and use the consistent information with the existing Python code as part of the parameter tuples passed to the exception. This ensures code consistency and avoids errors when other applications use your modules.

At the same time, the try-else t statement can be added with the else statement
It is no different from normal execution, that is, when no exception is detected in the try range, the else clause is executed.

Finally clause
The finally Clause executes a piece of code regardless of whether an exception occurs or not.


try:    try_suitefinally:    finally_suite

When an exception occurs in the try range, the system immediately jumps to the finally statement segment. When all code in finally is executed, the system continues to raise an exception.

Similarly, we also have the try-else t-else-finally statement, which can be used throughout the process.


Context Management
With statement
With is also used to simplify the code, hiding the underlying applications. A specific combination of try-retry T and try-finally is to ensure the unique allocation of shared resources and release it at the end of the task, such as files, thread resources, and simple synchronization, database Connection, etc. The goal of the with statement is to apply it in this scenario.
The purpose of the with statement is to remove the try, break t, and finally keywords from the flowchart and the Code related to resource allocation and release, rather than simply simplifying the Code to make it easy to use like try-release T-finally. The basic usage of the with syntax is as follows:
With context_expr [as var]:
This looks simple, but there is still some work to do behind it. This is not as easy as it looks, because the with statement cannot be used for any symbols in Python. It can only work on objects that support the context management protocol.
Objects supporting this Protocol are currently as follows:
Decimal. Context
Thread. LockType
Threading. Lock
Threading. RLock
Threading. Condition
Threading. Semaphore
Threading. BounderSemaphore
Use file as an Example

with open(r'\file.txt','r') as f:for eachLine in f:  # stuff with eachLine or f...

This code will complete the preparation, for example, trying to open a file. If everything is normal, assign the file object to f. then, use the iterator to traverse each row in the file. When the row is complete, close the file. Whether an exception occurs at the beginning, in the middle, or in the end of the Code, the cleaned code is executed and the file is automatically closed.

Trigger exception
In addition to the exception caused by the interpreter, the programmer also wants to trigger an exception when writing an API. Therefore, Python provides a mechanism for the programmer to explicitly trigger the exception, is the raise statement.
Raise is generally used as follows:

raise [SomeException [, arges [, trackback]]]

The first parameter, SomeException, is the name of the trigger exception. If yes, it must be a string, class, or instance. If there are other parameters (arg or traceback), it must provide SomeException.
The second symbol is the optional args to pass to the exception. This can be a separate object or a tuples of an object. If args is originally a tuples, it is passed to the exception zone for processing. If args is a separate object, a tuple with only one element is generated. In most cases, a single string is used to indicate the cause of the error. If the data is transmitted as a tuples, it usually consists of an error string, an error number, and a wrong address, such as a file.
The last parameter, traceback, is also optional. If yes, it is a new tracing object for exception-normal. The third parameter is useful when you want to re-raise an exception.

An assertion must be equivalent to a Boolean true decision. In addition, an exception also means that the expression is false.
Asserted statement Syntax:

assert expression[, arguments]

No action is taken for AssertionError.

Why is an exception?
No doubt, as long as the software exists, errors will always be lost. The difference is that in today's fast-paced computing world, our execution environment has changed, so we need to change error handling to accurately reflect the software development environment.
As the Internet and online e-commerce applications become increasingly popular, web servers will become the main customers of application software, meaning that applications cannot simply fail or crash, otherwise, a browser error occurs.
Some user-input data is invalid and must be converted into a non-error, so the running environment must be strong enough. We cannot simply return this error message. Instead, we should return enough information to ensure that users can learn usage experience smoothly.
Even in the face of an error, the application should be successfully aborted, so that the execution environment will not be disastrous.

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