"Python Learning-6" exception handling

Source: Internet
Author: User
Tags assert

Recently on the Internet to see a learning method called Feynman Learning method, that is, to learn a thing, to try to speak out to others, is a lesson-based learning.

The first step is to choose a concept that you want to understand, and then take out a piece of paper and write the concept on top of the white sheet. Second, imagine a scenario where you are about to impart this concept to someone to write down your interpretation of the concept on a white paper, as if you were teaching a new approach to the concept of a student. When you do this, you will be more aware of how much you understand about the concept and whether there are still areas of ambiguity. Third, if you feel stuck, review the study materials, and whenever you don't feel clear, go back to the original learning materials and re-learn the parts that make you feel unclear until you understand smoothly enough to be able to explain this part of the paper. The fourth step, in order to make your explanation easy to understand, the ultimate goal of simplifying language expression is to use your own language, rather than learning materials, the language of the course to explain the concept. If your explanation is lengthy or confusing, it means that your understanding of the concept may not be as smooth as you think you are, and you should try to simplify the language expression or establish an analogy with the knowledge you have, so that you can better understand it.

I think the Feynman study method is very good, can apply to the daily study. In this sense, blogging is a very sensible thing to do, because you are talking about what you understand.

Gossip is here, start learning today.

1, the handling of abnormal:

Python has very high exception handling and Java similarity, and the following are common exception handling code formats:

Try:    < statement >except < exception 1>:    < statement >except < exception 2>:    < statement >else:    < Statement >
Try:    < statement >finally:    < statements >

For catch statements, there are several ways to do this:

except:                                       < exception name >:                             #捕获单个异常except (Exception name 1, exception name 2):                     as< data >:                    as  < data;:            #捕获多个异常及附加信息

The code examples are as follows:

#!/usr/bin/python
L = [1,2,3,4,5];Print('---start---');Try: Print(l[6]);except:#except is executed when the code for the try has an exception. Except is a general class, and all exceptions can be captured Print('Error');Else:#else the code for try does not throw an exception when executed Print('No error');finally:#finally is executed regardless of whether the code for the try is abnormal Print('finally code');Print('---End---');#Other statements
#!/usr/bin/pythonL = [1,2,3,4,5];Print('---start---');Try:     Print(l[6]);finally:#finally is executed regardless of whether the code for the try is abnormal    Print('finally code');#An exception occurred, but the statement was executedPrint('---End---');#other statements, no execution
#!/usr/bin/python#different types of exception-sensitive processingL = [1,2,3,4,5];Print('---start---');Try:     Print(l[6]);exceptZerodivisionerror:Print('Zerodivisionerror');exceptindexerror as data:Print('Indexerror:'); Print(data); # Print exception information Else:#else the code for try does not throw an exception when executed    Print('No error');finally:#finally is executed regardless of whether the code for the try is abnormal    Print('finally code');Print('---End---');#Other Statements

The second code above, see two exceptions Zerodivisionerror and Indexerror, then what are the common exceptions?

Attributeerror calls an exception that            is thrown by a method that does not exist Eoferror encounters an exception                that is thrown at the end of a file Importerror                an exception caused by an import template error Indexerror                List out of bounds exception ioerror                 I/O operation exception Keyerror the exception that is thrown by using a                variable name that does not exist in the dictionary Nameerror an exception that is                raised by using a non-existent variable name Taberror                Statement indentation Incorrect exception valueerror                a value that does not exist in the search list throws an exception Zerodivisionerror        the exception that is thrown by the divisor of 0

In Python, if the processing of multiple exceptions is the same, you can write two exceptions together:

#!/usr/bin/python#different types of exception-sensitive processingL = [1,2,3,4,5];Print('---start---');Try:     Print(l[6]);exceptZerodivisionerror:Print('Zerodivisionerror');except(Indexerror,taberror):#two exceptions the same treatment    Print('Indexerror or Taberror');Else:#else the code for try does not throw an exception when executed    Print('No error');finally:#finally is executed regardless of whether the code for the try is abnormal    Print('finally code');Print('---End---');#Other Statements

2. Throwing Exceptions in code

The above is a python built-in exception, and in the script you can also use the raise statement to manually throw an exception . You can also use raise to throw exceptions in a class and pass data to the exception.

Raise exception name raise exception name, additional data raise class name

Simply use raise:

#!/usr/bin/pythonPrint('---start---');Try:     RaiseExceptionexceptException:Print('Exception');Else:     Print('No error');Print('---End---');#Other Statements

This should be the case in practical applications:

#!/usr/bin/pythondefAdd (x, y):ifx = = 0ory = =0:RaiseZerodivisionerror ('x or y is 0'); returnx+y;Try:    Print('Run 1'); A= Add (); Print(a); Print('Run 2'); b= Add (1, 0); Print(b); # There is no printing here because the last line is an exception exceptzerodivisionerror as data:Print(data);

Use of ASSERT statements: Assert statements can also throw exceptions, but unlike raise, an Assert statement throws an exception when the condition test is false.

Assert < Condition test >,< exception Additional information >

Example of an Assert:

 #!/usr/bin/python
ImportTracebackdefAdd (x, y):assertX! = 0 andY! = 0,'x or y is 0'; returnx+y;Try: Print('Run 1'); A= Add (); Print(a); Print('Run 2'); b= Add (1, 0); Print(b);except: #Traceback.print_exc () # Use the Traceback module in Python to track errorsF=open ("D:/tmp/pyerror.log",'A +') traceback.print_exc (file=F)#Enter an error in the fileF.flush ()

  asserts are used in conjunction with raise statements and if statements , but assert statements are typically used to develop self-test . The assert is valid only if __debug__ is true.

3. Custom exception Classes

In Python, you can create your own exception classes by inheriting the exception class:

#!/usr/bin/pythonclassMyerror (Exception):def __init__(self,data): Self.data=data; def __str__(self):return "Myerror:"+Self.data;Try:    RaiseMyerror ('0.0');exceptException as E:Print(e);

"Python Learning-6" 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.