Python exception handling, modules and packages

Source: Internet
Author: User
Tags assert

Markdownpad Document Errors are divided into two types of errors in the exception handler
    1. Syntax error: Unable to get past Python interpreter

    2. Logic error

Exception handling what is exception handling

The Python interpreter detects an error, triggers an exception, catches an exception when it occurs, and enters another processing branch if the capture succeeds, and the program does not crash, which is exception handling

Exception handling mechanism is to enhance the robustness and fault tolerance of the program

Common exceptions
AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性xIOError 输入/输出异常;基本上是无法打开文件ImportError 无法引入模块或包;基本上是路径问题或名称错误IndentationError 语法错误(的子类) ;代码没有正确对齐IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]KeyError 试图访问字典里不存在的键KeyboardInterrupt Ctrl+C被按下NameError 使用一个还未被赋予对象的变量SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)TypeError 传入对象类型与要求的不符合UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它ValueError 传入一个调用者不期望的值,即使值的类型是正确的

Basic syntax

try:    被检测的代码块except 异常类型 [as x]:    try中一旦检测到异常,就执行这个位置的逻辑except 其他异常类型 [as e]:    执行此处的逻辑
try:    被检测的代码块except Exception as x:    print(e)

Exception Universal exception, no matter what exception is thrown can be captured, in a way to deal with, but if you want to different exceptions need to customize different processing logic, or to use multi-branch processing

Other forms of the exception

s1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)#except Exception as e:#    print(e)else:    print(‘try内代码块没有异常则执行我‘)finally:    print(‘无论异常与否,都会执行该模块,通常是进行清理工作‘)

Proactively throwing exceptions

#_*_coding:utf-8_*_try:    raise TypeError(‘类型错误‘)except Exception as e:    print(e)

Custom exceptions

#_*_coding:utf-8_*_class EgonException(BaseException):    def __init__(self,msg):        self.msg=msg    def __str__(self):        return self.msgtry:    raise EgonException(‘类型错误‘)except EgonException as e:    print(e)

Assertion

1 # assert 条件2  3 assert 1 == 14  5 assert 1 == 2

Try: Except ways to compare the benefits of the IF way

    1. Separate the error handling from the real work

    2. Code is easier to organize, clearer, and complex tasks are easier to implement

    3. There is no doubt that it is safer to fail the program accidentally because of some minor negligence.

Try: Except this exception handling mechanism is to replace if that way, allowing your program to enhance robustness and fault tolerance without sacrificing readability

Exception types are customized for each exception (Python unifies classes and types, type is a Class), and for the same exception, a except can be caught, an exception that can handle multiple pieces of code at the same time (without ' writing multiple if judgments ') reduces code and enhances readability

When to use exception handling

Try...except should be used sparingly, because it is in itself a program you attach to the exception of the logic of the process, and your main work is not related, this kind of things add more, will lead to your code readability is poor, only in some exceptions can not be predicted, you should add Try ... Except, other logic errors should be corrected as much as possible.

Modules and packages what is a module?

A module is a file that contains the Python definition and declaration, and the filename is the suffix of the module name plus the. py

Why use a module?

with the development of the program, more and more functions, in order to facilitate management, usually the program into a file, so that the structure of the program is more clear, easy to manage, at this time not only can the file as a script to execute, but also as a module to import into other modules, The reuse of functions is realized.

Importing the module triggers the following events:

    • First thing: Create a namespace to hold the names defined in the imported module

    • Second thing: Execute the imported module based on the namespace you just created

    • The third thing: Create a module name to point to the namespace, module. Operation by name

How to use Modules

A module can contain definitions of executable statements and functions that are intended to initialize modules that execute only when the module name is first encountered when importing an import statement (the import statement can be used anywhere in the program and is imported multiple times for the same module) , to prevent you from repeating the import, Python is optimized by loading the module name into memory after the first import, and the subsequent import statement only adds a reference to the module object that has loaded the large memory and does not re-execute the statements within the module.

import syssys.module #可以查看当前已经加载的模块

can alias the module import time as Mytimeprint (Mytime.time ())

You can import multiple modules on a single line, but this is not recommended

import sys,re,os  #最好分多行进行模块的导入
From...import ...

modules imported using this method can use the name of the namespace in the imported module directly, instead of using the module name. The way of the name, But at this point, if there is a duplicate of the effect of the overlay, the principle is that the variable assignment in Python is not a storage operation, but only a binding relationship

from...import*

You can import all names that do not begin with an underscore to the current location, but it is generally not recommended because you do not know which names are imported and may overwrite names that have already been defined and are not readable.

You can use all to control * (when a new version is released)

__all__=[‘name1‘,‘name2‘]  #这样在另外一个文件中导入时就只能导入列表中的这两个名字
Execute the module as a script

The module name can be viewed through the module's global variable name name = 'main' #当做脚本运行

Module Search Path

Load the module to see if the memory load---and then find the same name of the built-in module---and then find the directory list Sys.path

It is important to note that custom module names do not duplicate the system's built-in modules

Package

A package is a way to organize the Python module namespace by using the '. Module name '

    1. The essence of the package is a directory containing the init. py file

    2. In the case of the import, the left side of the point must be a package, but after import there is no such restriction when used, the left side of the point can be a package, module, function, class

    3. Imported modules from the after import must be a clear one, not a point, or there will be a syntax error

    4. The first time the package is imported or any other part of the package, the init. py file under the package is executed sequentially, and the file can be empty or put some code to initialize the package

Absolute Import and relative import
    • Absolute import: Start with top-level packages

    • Relative import: With '. ', '. ' As a starting point (can only be used in one package and not in different directories)

It is important to note that you can import the built-in or third-party modules with import, but to absolutely avoid importing the submodule of the custom package using import, you should use From...import ... Absolute or relative import, and the relative import of the package can only be used from the form

Python exception handling, modules and packages

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.