Python contains a set of try: Error handling mechanism of except...finally
Python built-in try...except...finally to handle errors is very convenient. When an error occurs, it is critical to parse the error message and locate the code location where the error occurred.
Try: Except...else. Finally
Run the program first.
Try:#execute code that may cause an error to occur first Print('Try ...') R= 10/int ('2') Print('Result:', R)exceptValueError as E: Captures the type of exception and modifies itPrint('ValueError:', E)exceptZerodivisionerror as E:Print('Zerodivisionerror:', E)Else:#This code card executes when no error occurs Print('No error!')finally:#The end of the process body is executed whether or not the error occurs Print('finally ...')Print('END')
If you do not know what the error will be, but also make sure that this code is working properly, you can use
defFoo (s):return10/Int (s)defBar (s):returnFoo (s) * 2defMain ():Try: Bar ('0') exceptException as E:#exception allows you to do this without specifying the cause of the error, as long as an exception is detected Print('Error:', E)finally: Print('finally ...')
#python built-in logging module
#可以记录下来错误 through the configuration, logging you can also log errors into the journal file, to facilitate the subsequent troubleshootingImportLoggingdefFoo (s):return10/Int (s)defBar (s):returnFoo (s) * 2defMain ():Try: Bar ('0') exceptException as E:logging.exception (e) main ()Print('END')
You can also throw an exception artificially
classFooerror (valueerror):Passa= 1ifA! =0:RaiseFooerror ('Invalid value:%s'%s)Else: Print('OK')-----------------------------------Traceback (most recent): File"__slots__.py of the c:/users/hxsd/pycharmprojects/helloworld/class", line 47,inch<module>RaiseFooerror ('Invalid Fooerror')#Custom-Thrown error message__main__. Fooerror:invalid Fooerror
How breakpoint debugging can be used when debugging
Python's built-in handling exception mechanism and debugging