Python20 error, debugging

Error, debugging

  • Error handling:在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因
    • try ... except ... finally ... error handling mechanism
      • Code:
        `` `
        # exception handling
        # try ... except ... finally ...

        '' '
        When we think some of the code may be wrong, you can try to run this code,
        if executed wrong, then the following code will not continue, but the error-handling code to jump directly to that except statement block ,
        after executing except, if there is finally block, the finally block execute, so far, it is finished.
        '' '

        try: # statement is executed first come try print (10/0) in the block of statements
        Print (10/0)
        except the ZeroDivisionError: # try block error, execute block except statement, except statement if the block is not being given the try block is not performed
        print ( '! except statement is executed')
        finally: # no matter except whether the final will execute the finally block, you can not finally statement
        print ( '! finally statement is executed')
        Print ( 'test is completed!')
        `` `
      • operation result:
        nnRVL8.png
    • Record error: Python built-in logging module can easily record the error message
      • Code:
        `` `
        # built-in functions logging error messages are logged

        # Is also a mistake, but after the program finishes printing error message continues, and exit to normal:
        Import logging
        DEF do_ZeroError (vaule):
        return 10 / vaule

        def man():
        try:
        do_ZeroError(0)
        except Exception:
        logging.exception(Exception)
        man()
        print('End')
        ```
      • operation result:
        nnhGOP.png
    • Throw an error:raise
      • Code:
        `` `
        # raise throw an error

        # A custom error, error class inheritance need
        class TestError is (a ValueError):
        Pass
        DEF do_Return (I):
        IF I == 0:
        The raise TestError is ( 'wrong!')
        Return 10 / I

        print(do_Return(0))
        ```
  • Debugging: means to check whether correct operation of the program
    • Assertion: assertmean, n = 0 expression should be True, otherwise, according to the logic of the program is running, the code behind will certainly be wrong!.
    • Example:
      nnbodI.png
    • logging:
    • Example:
      nnqnT1.png

Guess you like

Origin www.cnblogs.com/thloveyl/p/11469291.html