Exception, python error handling

Excerpt: https://www.liaoxuefeng.com/wiki/1016959663602400/1017598873256736

 

 

Error Handling

High-level language will use a built-in try...except...finally...error handling, more efficient handling errors,

Programmers write code without having to own error handling.

 

try

try:
    print('try...')
    r = 10 / int('2')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
else:
    print('no error!')
finally:
    print('finally...')
print('END')

 

 

  • If there are errors, according to different types of errors occur, except using a different process.
    • int ( 'a') will start ValueError
    • 10/0 triggers ZeroDivisionError.
  • Otherwise there are no errors on behalf of, the execution else.
  • Finally, finally we have to perform

 

Common error types and inheritance

Look documents Built-in Exceptions

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

 

try the benefits

Call across multiple layers. Main () function call to bar (), bar calls foo (), as long as the error occurs during, try will be processed.

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...')

 

 

Call Stack

If the error is not caught, it would have been throwing up, finally captured the Python interpreter prints an error message and then the program is terminated.

The error message isTraceback (most recent call last)...。它是一个错误路径。可以在最后查看错误原因,定位错误位置。

 

logging module

You can record the error information to the log. And let the program continue.

# err_logging.py

import logging

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

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

def main():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e)

main()
print('END')

 

 

Throw an error

Error is class, capturing a mistake is to capture an instance of the class. So, the error is an error instance according to the situation deliberately created.

There are various types of error built-in function. Can also write your own functions, then throws an error.

# err_raise.py
class FooError(ValueError):
    pass

def foo(s):
    n = int(s)
    if n==0:
        raise FooError('invalid value: %s' % s)
    return 10 / n

foo('0')

 

  • A write error class FooError.
  • A raise statement, the generated instance FooError.

Try to use the built-in functions. Such as ValueError, TypeError

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/chentianwei/p/11871228.html