Exception handling related statements in Python Basic learning notes _python

Source: Internet
Author: User
Tags assert exception handling integer division in python

An exception is an action taken outside the normal control stream because of an error in the program. It is divided into two stages, the first stage is to throw an exception error, when the system detects errors and aware of exceptional conditions, the interpreter (or can be a programmer to throw an exception) will raise an exception notification before the control flow error occurred, Handling of exceptions occurs in the second phase, after an exception is raised, you can invoke many different actions, either ignoring the error, or logging the error without taking any action, terminating the procedure after taking remedial action, or trying to continue executing the program after the impact of the Jiang Qing problem.
A language like Python that supports raising and handling exceptions can give developers the ability to detect errors when they occur, and to take more reliable remedial action.
Python uses an Exception object (Exception object) to represent an exception, and if an exception is thrown if it is not processed or caught, the program automatically calls backtracking (Traceback) to terminate execution

>>> 1/0
Traceback (most recent call last):
 File "", Line 1, in
Zerodivisionerror:integer division or Modulo by Zero
>>>


Exceptions in Python
The Python interpreter detects exceptions such as:
1) Nameerror: Attempt to access an undeclared variable
2) Zerodivisionerror: Divisor is zero
3) Syntaxerror:python syntax error
4) Indexerror: Requested index out of sequence range
5) Keyerror: Request a nonexistent dictionary keyword
6) IOError: input/Output error
7) Attirbuteerror: Attempting to access unknown object properties
8) TypeError: Raised when a built-in operation or function is applied to an object of the wrong type
9) ValueError: The built-in operation or function is applied to the correct type of object, but a value that is not appropriate for that object reference is raised

The programmer explicitly triggers the exception:
Raise statement:

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


Detecting and Handling exceptions
Exceptions can be detected by try statements, and there are two main forms of implementation: Try-except and try-finally:

Try-except statement
defines a section of code for exception monitoring and provides a mechanism for handling exceptions

Try:
  try_suite #进行监控的代码
except exception[, reason]:
  except_suite #异常处理的代码
[except exception2[, Reson2]:
  Except_suite2 # handles a variety of possible exceptions that may occur in a try statement
[else:
  else_suite #try中语句执行没有异常被检测到
[finally:
  Finally_suite #无论如何均会执行]]]


try-finally Statement
finally-mode statements are not used to catch exceptions, but to maintain consistent behavior regardless of whether an exception occurs or not, and finally code snippets are executed regardless of whether an exception is fired in a try

Try:
  try:
    try_suite
  except:
    excetp_suite
finally:
  finally_suite

is equivalent to:

Try:
  try_suite
except:
  excetp_suite
finally:
  finally_suite

Assert

The assert in Python is similar to the ASSERT () function in C language,
The main function is to ensure that a certain condition in the program must be true in order for the program to execute, or terminate the program execution and trigger the Assertionerror error
It can be treated as a relatively advanced point of exception handling
Grammar:

 
 

(without parentheses)
Where the expression1 represents the judgment condition that the program continues to execute, continues as true, terminates for the false program, and throws the descriptive information given by expression2

>>> a=10
>>> assert a<=10, "Error"
>>> a = one
>>> assert a<=10, " Error "
Traceback (most recent):
 File" <stdin> ", line 1, in <module>
assertionerror: Error

Equivalent to:

If A>10:raise assertionerror ("Error")

Description
Assert statements are generally used for debugging during program writing, adding them to the Python source code without avoiding the impact of compilation performance.
It is recommended that you remove assert statements as much as possible and set __debug__ this built-in variable to false, that is, to add parameters to the Run command line

python-0 test.py

(This is actually similar to the compile parameter-D in C language)

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.