Python Learning-Basics (eight)

Source: Internet
Author: User
Tags integer division

Python built-in a set of try...except...finally ... error-handling mechanism;

Try:    print ' Try '    r = 10/0    print ' result: ', rexcept Zerodivisionerror, E:    print ' except: ', efinally:
   
    print ' finally ' results: Tryexcept:integer division or modulo by zerofinally
   


Finally statement blocks are bound to be executed;

except The statement block is appended with a else else statement:

Try:    print ' Try '    r = 10/1    print ' result: ', rexcept Zerodivisionerror, E:    print ' except: ', Eelse:    PR int ' no error ' finally:    print ' finally ' Result: tryresult:10no errorfinally


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

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

The logging module can be imported to record exceptions to the log file;

Import logging

Logging can specify the level of information: Debug,info,warning,error These levels, you can specify the log level of the file

Import Logginglogging.basicconfig (Level=logging.info)


Another benefit of logging is that with a simple configuration, a statement can be output to a different place at the same time, such as the console and the file


Rasie throws the error, which not only solves the situation where you do not know how to handle it, but also changes the type of throw error;

Try:    print ' Try '    r = 10/0    print ' result: ', rexcept Zerodivisionerror, E:    print ' except: ', e    raise Va Lueerror (E) Finally:    print ' finally ' Result: Tryexcept:integer division or modulo by Zerofinallytraceback (most recent Call last):  File "f:/hz_viking/pycharmprojects/django_demo/webbase/apps/cm/syc/variblescope.py", line 353, in <module>    raise ValueError (e) Valueerror:integer division or modulo by zero


Assertion:

use ASSERT (assert) to replace print;

def test (i):    try:        print ' Try '        assert I! = 0,  ' i is zero ' # assertion I is 0, if False, the following instructions will be printed    except Zerodivisionerror, E:        print ' except: ', e        raise ValueError (E)    finally:        print ' finally ' test (0) Result: Traceback (most recent):  File "f:/hz_viking/pycharmprojects/django_demo/webbase/apps/cm/syc/ variblescope.py ", Line 358, in <module>    test (0)  File" f:/hz_viking/pycharmprojects/django_demo/ webbase/apps/cm/syc/variblescope.py ", line 349, in Test    assert I! = 0,  ' I was zero ' assertionerror:i is zero


If the program is filled with assert, and print > No better than that. However, the Python interpreter can be started with the -o parameter to close assert

Python-o err.py


Unit tests:

in order to write unit tests, we need to introduce the unittest module that comes with Python:

Import Unittestclass testdict (unittest. TestCase):    def test_init (self):        d = {' Java ': ' Diffcult ', ' python ': ' Midle '}        self.assertequal (D.get (' Java '), ' Diffcult ')


When writing unit tests, we need to write a test class from UnitTest. TestCase inheritance.

The method that begins with test is the method of testing, and the method that does not begin with test is not considered a test method and is not executed when the test is performed.

Unit testing can effectively test the behavior of a program module and is a confidence guarantee for future refactoring code.

Test cases for unit tests overwrite common input combinations, boundary conditions, and exceptions.

Unit test code is very simple, if the test code is too complex, then the test code itself may have a bug.

Unit testing does not mean that the program is not a bug, but not through the program must have a bug.

Python Learning-Basics (eight)

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.