try/except/finally

Python is no exception, like other high-level language, built a try ... except ... finally ... the error handling mechanism
when deemed some of the code may be wrong, you can try to run this code

 

try ... except ... finally ... mechanism

  If you do wrong, then the following code will not continue, but the error-handling code to jump directly to that except a statement block
  if finally block, after performing except, finally block is executed, so far, finished
  with or without error, finally statement at all would be executed

    try:
        ......
    except ZeroDivisionError as e:
        print('except:', e)
    finally:
        print('finally...')

 

Wrong inheritance

  Python is actually wrong class, all error types are inherited from BaseException
  so use except to note is that it not only captures the error corresponding to the class, subclass will catch the error corresponding to

  such AError is BError parent If prior except AError, except bError after,
  but if the error is captured except AError, and also belongs to the bError error, but the error will not be captured except bError

  Python all errors are derived from BaseException class
  common error types and inheritance, please refer to the link: https: //docs.python.org/3/library/exceptions.html#exception-hierarchy

    the try : 
        ...... 
    except ValueError AS E:
         Print ( ' ValueError ' )
     except UnicodeError AS E: 
     # Second except not capturing UnicodeError never, because UnicodeError is a subclass of ValueError, if any, by the first except for a captured 
        Print ( ' a UnicodeError ' )

 

Calls across multiple layers

  Use try ... except to catch errors and a huge advantage is that you can call across multiple layers
  such as main () function call to bar (), bar () calls foo (), if foo () error, as long as the main () you can capture
  you need not go wrong in every possible place to catch the error, as long as the appropriate level to catch errors can, therefore greatly reducing the write try ... except ... finally trouble

    def foo(s):
        return 10 / int(s)

    def bar(s):
        return foo(s) * 2

    def main():
        try:
            bar('0')
        except Exception as e:
            print('Error:', e)
        finally:
            print('finally...')

 

Guess you like

Origin www.cnblogs.com/shiliye/p/11008792.html