Python Learning-Exceptions

Source: Internet
Author: User
Tags assert

I. Definition of exception handling

The Python interpreter detects an error, triggering an exception (also allowing the programmer to trigger an exception himself)

Programmers write specific code that is specifically designed to catch this exception (this code is independent of the program logic and is related to exception handling)

If the capture succeeds, go to another processing branch, execute the logic you've customized for it, and the program won't crash, which is exception handling

Two. Usage of exception handling

In order to ensure the robustness of the program and fault tolerance, that is, when encountering errors, the program does not crash, we need to handle the exception,
1, if the condition of the error is predictable, we need to handle it with if and prevent it before the error occurs.

age1 = 10while True:    age=input(‘输入: ‘)        if age.isdigit(): #只有在age为字符串形式的整数时,下列代码才不会出错,该条件是可预知的        age=int(age)        if age == age1:            print(‘you got it‘)            break

  
2, if the error occurs when the condition is unpredictable, you need to use the try: Except: Processing after an error has occurred

Three. The basic syntax is
try:    被检测的代码块except 异常类型:    try中一旦检测到异常,就执行这个位置的逻辑

Example

try:    f=open(‘a.txt‘)    g=(line.strip() for line in f)    print(next(g))    print(next(g))    print(next(g))    print(next(g))    print(next(g))except StopIteration:    f.close()

  

Four. Try...except ... The detailed usage

We put statements that could have errors in the Try module and use except to handle exceptions. Except can handle a specialized exception, or it can handle an exception in a set of parentheses, and if no exception is specified after except, all exceptions are handled by default. Every try must have at least one except
1. The exception class can only handle the specified exception condition and cannot be processed if a non-specified exception

s1 = ‘hello‘try:    int(s1)except IndexError as e: # 捕获到异常,程序直接报错    print(e)

  
2. Multi-Branch

s1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)

  
3. Universal Anomaly exception

s1 = ‘hello‘try:    int(s1)except Exception as e:    print(e)

  
4. Multi-Branch +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)

  
5. Exception of other institutions (try...finally syntax)

The try...finally statement executes the final code regardless of whether an exception occurs. The syntax is as follows:

try:<语句>finally:<语句>    #退出try时总会执行raise

Example:

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(‘无论异常与否,都会执行该模块,通常是进行清理工作‘)

  
6. Active trigger exception (raise statement)

We can use the raise statement to trigger the exception ourselves, and the raise syntax is as follows:

raise [Exception [, args [, traceback]]]

The type of exception in the statement is an exception (for example, the Nameerror) parameter is an exception parameter value. This parameter is optional and if not provided, the exception parameter is "None".

The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.

Example:

An exception can be a string, a class, or an object. The Python kernel provides exceptions, most of which are instantiated classes, which are parameters of an instance of a class.

It is very simple to define an exception as follows:

def functionName( level ):    if level < 1:        raise Exception("Invalid level!", level)        # 触发异常后,后面的代码就不会再执行try:    raise TypeError(‘类型错误‘)except Exception as e:    print(e)

  
7. Custom Exceptions

By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.

The following is an example of a baseexception-related instance in which a class is created and the base class is Baseexception, which is used to output more information when the exception is triggered.

In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, the variable e is used to create an instance of the Networkerror class.

class Networkerror(BaseException):    def __init__(self,msg):        self.msg=msg    def __str__(self):        return self.msgtry:    raise Networkerror(‘类型错误‘)except Networkerror as e:    print(e)

8. Assert: Assert condition

assert 1 == 1  #不会报错assert 1 == 2  #会报错assert 1 != 1  #会报错

Chestnuts:

def is_huiwen_num(num):    snum = str(num)    return snum == snum[::-1]# 如果希望程序中的所有assert语句不执行, 那么给python -O 脚本名if __name__ == "__main__":    assert is_huiwen_num(100) == True    #会在这里直接抛出异常,中断执行过程    assert  is_huiwen_num(101) == True    print("assert")运行结果:Traceback (most recent call last):  File "/home/kiosk/PycharmProjects/python_projects/ttttt.py", line 7, in <module>    assert is_huiwen_num(100) == TrueAssertionError
Five. Common types of anomalies

Different exceptions in Python can be identified in different types (Python unifies classes and categories, types as classes), and an exception identifies an error.
Common syntax errors

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

Python Learning-Exceptions

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.