Python Day 9 (5) Error handling

Source: Internet
Author: User
Tags error handling

One: Error, Debug and test

1 errors in the program run:

A problem with programming a program, which we often call bug,bug, must be fixed.

b user input can be caused by checking user input to do the corresponding processing.

c there is a class of error is completely unable to predict during the program running, such as when writing to the file, the disk is full, write not in, or fetch data from the network, the network suddenly broke off. This type of error, also known as an exception, is usually handled in a program, otherwise the program terminates and exits due to various problems.

2 Debugging: We also need to track the execution of the program, to see whether the value of the variable is correct, this process is called debugging. The PDB for Python allows us to execute the code in a single step.

3 testing: Finally, writing tests is also important. With good testing, you can run it repeatedly after the program has been modified to ensure that the program output conforms to the tests we write.

Two: Error handling (with try......except......finally)

1 (use try......except......finally to catch errors)

1 Try:2     Print('Try ...')3R = 10/04     Print('Result:', R)5 exceptZerodivisionerror as E:6     Print('except:', E)7 finally:8     Print('finally ...')9 Print('END')

A When we think that some code may be wrong , it can be used try to run the code, if the execution error, the subsequent code will not continue to execute, but directly to the error handling code, that is, the except statement block, except after execution, if there is a finally statement block, then the Line finally statement block, at this point, execution is complete.

b errors can be of many kinds, and if different types of errors occur, they should be handled by a different except block of statements. Yes, there can be multiple except to catch different types of errors:

int()The function may be thrown ValueError , so we use one except capture ValueError , with another except capture ZeroDivisionError .

In addition, if no error occurs, you can except add one after the statement block else and automatically execute the statement when no error occurs else :

1 Try:2     Print('Try ...')3R = 10/int ('2')4     Print('Result:', R)5 exceptValueError as E:6     Print('ValueError:', E)7 exceptZerodivisionerror as E:8     Print('Zerodivisionerror:', E)9 Else:Ten     Print('No error!') One finally: A     Print('finally ...') - Print('END')

C Python's error is also class, all the error types are inherited from BaseException , so in the use except of note that it not only captures the type of error, but also its subclasses "clean sweep". Like what:

1 Try : 2     foo ()3except  valueerror as E:4     Print ('valueerror') 5 except Unicodeerror as E: 6     Print ('unicodeerror')

The second one except is never caught UnicodeError , because UnicodeError ValueError the subclass, if any, is also captured by the first one except .

All of Python's errors are BaseException derived from the class, common error types and inheritance relationships look here:

Https://docs.python.org/3/library/exceptions.html#exception-hierarchy

D try...except There is also a huge benefit of using catch errors, which can span multiple layers of calls, such as function main() calls, foo() foo() calls, and bar() result errors, at which bar() point they can be processed as soon as they are main() captured:

1 defFoo (s):2     return10/Int (s)3 4 defBar (s):5     returnFoo (s) * 26 7 defMain ():8     Try:9Bar'0')Ten     exceptException as E: One         Print('Error:', E) A     finally: -         Print('finally ...')

In other words, there is no need to catch errors in every possible error, as long as the error is captured at the appropriate level. In this way, it greatly reduces the try...except...finally trouble of writing.

2 Call Stack (no try......except......finally to capture)

If the error is not captured, it is thrown up and then caught by the Python interpreter, prints an error message, and the program exits.

1 def Foo (s): 2     return / int (s)  3  4def  Bar (s):  5      Return foo (s) * 2 6  7def  Main ():  8     Bar (' 0 ' )  9 Main ()

The results are as follows:

1 $ python3 err.py2 Traceback (most recent):3File"err.py", line 11,inch<module>4 Main ()5File"err.py", Line 9,inchMain6Bar'0')7File"err.py", line 6,inchBar8     returnFoo (s) * 29File"err.py", Line 3,inchFooTen     return10/Int (s) OneZerodivisionerror:division by Zero

However, to parse the wrong call stack information yourself, locate the wrong location.

3 Logging Errors

If you do not catch an error, it is natural for the Python interpreter to print out the error stack, but the program is ended. Now that we can catch the error, we can print out the error stack, analyze the cause of the error, and let the program go on.

Python's built-in logging modules make it very easy to log error messages:

1 ImportLogging2 3 defFoo (s):4     return10/Int (s)5 6 defBar (s):7     returnFoo (s) * 28 9 defMain ():Ten     Try: OneBar'0') A     exceptException as E: - logging.exception (e) -  the Main () - Print('END')

The same error occurs, but the program continues to execute after the error message is printed and exits normally

1 $ python3 err_logging.py2 ERROR:root:division by Zero3 Traceback (most recent):4File"err_logging.py", Line 13,inchMain5Bar'0')6File"err_logging.py", Line 9,inchBar7     returnFoo (s) * 28File"err_logging.py", line 6,inchFoo9     return10/Int (s)Ten zerodivisionerror:division by Zero OneEND

Through the configuration, the logging error can also be recorded in the log file, to facilitate the subsequent troubleshooting.

4 Throwing errors

Because the error is class, capturing an error is capturing an instance of the class. As a result, errors are not generated in a vacuum, but are intentionally created and thrown. Python's built-in functions throw many types of errors, and the functions we write ourselves can also throw errors.

If you want to throw an error, you can first define an incorrect class, choose a good inheritance relationship, and then raise throw an instance of the error with the statement.

1 #err_raise.py2 classFooerror (valueerror):3     Pass4 5 defFoo (s):6n =Int (s)7     ifn==0:8         RaiseFooerror ('Invalid value:%s'%s)9     return10/NTen  OneFoo'0')

execution, you can finally trace to our own definition of the error

1 $ python3 err_raise.py2 Traceback (most recent):3File"err_throw.py", line 11,inch<module>4Foo'0')5File"err_throw.py", line 8,inchFoo6     RaiseFooerror ('Invalid value:%s'%s)7 __main__. Fooerror:invalid value:0

Define our own error types only when necessary. If you can choose a built-in error type that Python already has (for example ValueError , TypeError ), use the Python built-in error type as much as possible.

Python Day 9 (5) Error handling

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.