Python Full stack Development Foundation "supplemental" Exception handling

Source: Internet
Author: User

I. Errors and anomalies

Errors are unavoidable in the program, and there are two types of errors

1. Syntax error: (this error, the syntax of the Python interpreter can not be detected, must be corrected before the program executes)

2. Logic Error: (logic error), such as inappropriate user input and a series of errors

So what's an anomaly?

An exception is a signal that an error occurs while the program is running, and in Python the exception that is triggered by the error is as follows. After an exception occurs, the code after the exception is not executed

Exception types: Different exceptions in Python can be identified in different types (Python unifies class and type, type as Class).

Different class objects identify different exceptions, and an exception identifies an error

Common exceptions:

# More Exception Arithmeticerrorassertionerrorattributeerrorbaseexceptionbuffererrorbyteswarningdeprecationwarningenvironmenterroreo Ferrorexceptionfloatingpointerrorfuturewarninggeneratorexitimporterrorimportwarningindentationerrorindexerrorioerrorkeybo Ardinterruptkeyerrorlookuperrormemoryerrornameerrornotimplementederroroserroroverflowerrorpendingdeprecationwarningrefere Nceerrorruntimeerrorruntimewarningstandarderrorstopiterationsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortypeerro Runboundlocalerrorunicodedecodeerrorunicodeencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerro Rwarningzerodivisionerror

  

Second, exception handling

1. What is 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

2. Why do I have to do exception handling?

The Python parser goes to execute the program, detects an error, triggers an exception, the exception is triggered and is not processed, the program terminates at the current exception, and the code behind it does not run, who will use a software that is running with a sudden crash.

So you have to provide an exception handling mechanism to enhance the robustness and fault tolerance of your program.

3. How to perform exception handling

First of all, the exception is caused by a program error, grammatical errors are not related to exception handling, must be corrected before the program runs

① Using if judgment

Num1=input (' >>: ') #输入一个字符串试试if num1.isdigit ():    int (NUM1) #我们的正统程序放到了这里, the rest belongs to the exception handling category Elif Num1.isspace ():    print (' input is a space, execute my logic here ') Elif len (num1) = = 0:    print (' Input is empty, execute my logic here ') Else:    print (' Other situation, execute my logic here ') ' "Problem One: we only add exception handling for the first piece of code using if, but these if are not related to your code logic, so your code will not be easy to read because of poor readability." This is just a small logic in our code, and if there is more logic like that, then every time you need to judge the content , it will be inverted our code is particularly verbose. ‘‘‘

Summarize:

1.if-Judging exception handling can only be done for a piece of code, for the same type of error for different pieces of code you need to write the duplicate if to handle it.

2. Frequent writes in your program are not related to the program itself, and if it is related to exception handling, it will make your code very readable.

3.if is able to solve the anomaly, but there are problems, so do not jump to the conclusion that if can not be used for exception handling.

②python customizes a type for each exception, and then provides a specific syntax structure for exception handling

1. Syntax:

Try:     code block except exception type:     When an exception is detected in try, the logic for this position is executed

2. The exception class can only be used to handle the specified exception condition, and cannot be handled if a non-specified exception

S1 = ' Hello ' try:    int (s1) except Indexerror as E:    print (e) <br> #没有捕获到异常, program direct error

3. Multi-Branch

Catch exception num= input (' num:>> ') Try:    f= Open (' File ', ' W ')    # int (num)    # l = []    # l[10000]    # 1/0    # D IC = {' K ': ' V '}    # dic[' K2 '    ) print ('-----------') except ValueError:    print (' Please enter a number ') except Nameerror as Name_e:    print (name_e)    print (' ======= ') except Indentationerror as Name_e:    print (name_e) except Indexerror as Name_e:    print (name_e) except SyntaxError as Name_e:    print (name_e) except Zerodivisionerror as Name_e:    print (name_e) except Attributeerror as Name_e:    print (name_e) except Keyerror as Name_e:    print ( NAME_E) # except Exception as e:#     print (E, ' abnormal ') Else: #如果上面出现问题了, do not execute else, if all is correct, the content of else will be executed (the payment process can use else)    print (' else executed ') finally:  #不过这段代码出没出问题, execute the content here    F.close () print (' finally ')

4. Universal exception: can catch any exception

S1 = ' Hello ' try:    int (s1) except Exception as E:    print (e)

5. Proactively triggering exceptions

Try:    raise Attributeerror (' wrong wrong ') except Attributeerror as E:    print (e)

6. Custom Exceptions

Class Egonexception (baseexception):    def __init__ (self,msg):        self.msg = msg    # def __str__ (self):   You can not write this method, because the Baseexception parent class has already implemented the    #     return self.msgtry:    raise Egonexception (' Egon out of the ordinary ') except Egonexception as E:    print (e)

7. Assertions

#断言: An exception will be thrown judgment, once the condition is established, once the error is not established, it will not perform the following assert 1==2if 1==2:    print () print (' haha ')

8.try.. Except ways to compare the benefits of the IF way

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

Use try: The way of except

1: Separate the error handling from the real work
2: Code easier to organize, clearer, complex tasks easier to implement;
3: No doubt, more secure, not due to some small negligence to make the program accidentally collapsed;

Iii. when to use exception handling

Try...except should be used sparingly, because it is an exception-handling logic that you attach to your program, which is not related to your main work.

This kind of things add more, will lead to your code readability is poor, only in some abnormal unpredictable circumstances, should add try...except,

Other logic errors should be corrected as much as possible

  

Python Full stack Development Foundation "supplemental" Exception handling

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.