This is the 26th day of my participation in Gwen Challenge

Error handling mechanismtry... except... finally...

The use of this method is similar to the Try-catch-finally method in Java, except that there is an else to indicate that there is no exception. Note that the class of the caught exception is from the subclass to the parent class

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

# Print result:
# try...
# the result: 5.0
# no error!
# finally...
# END
Copy the code

If you are familiar with Java, you will see the difference in the catch. If you are familiar with Java, you will see the difference in the catch. If you are familiar with Java, you will see the difference in the catch

Call stack & record error

Python’s built-in logging module makes error logging very easy: It can also be configured to log errors to a log file for later troubleshooting.

Bug-finding operations are usually located directly at the end of the page

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

# Print result:
# ERROR:root:division by zero
# Traceback (most recent call last):
# File "
      
       ", line 11, in main
      
# bar('0')
# File "
      
       ", line 7, in bar
      
# return foo(s) * 2
# File "
      
       ", line 4, in foo
      
# return 10 / int(s)
# ZeroDivisionError: division by zero
# END
Copy the code

This log feels no special ~ after all, everyone is a log ๐Ÿ˜„

Throw an error

This is the same as when Java throws exceptions (except that Java cannot catch errors, which are usually virtual machine or system errors such as OutofMemoryErrors). Exceptions can be resolved, such as RuntimeException and so on.

Errors that cannot be determined by the lower level are thrown to the higher level and raised with the raise statement

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

def bar() :
    try:
        foo('0')
    except ValueError as e:
        print('ValueError! ')
        print(e)

bar()
Copy the code

It’s a little different here, this error can be thrown up again

The last

Welcome friends to discuss the question ~

If you think this article is good, please give it a thumbs-up ๐Ÿ˜

Let’s start this unexpected meeting! ~

Welcome to leave a message! Thanks for your support! ใƒพ(โ‰งโ–ฝโ‰ฆ*)o go!!

I’m 4ye. We should… next time. See you soon!! ๐Ÿ˜†