Exception handling
When the code is running, bugs can occur for a variety of reasons, and the program will run out of trouble when it encounters a bug, while in daily production The program is not interrupted for long periods of time. Therefore, we need to do a good job of exception handling beforehand.
Abnormal
Print (x) # General error will print a bunch of red errors
Exception Handling: for more reasonable handling of code errors that may occur
Try: Print(x)exceptNameerror as Error:Print('Error:%s'% error)#Error: Name ' x ' is not definedElse: Print('no exception execution code for else')Print('the other code')#will execute normally
In the example above, the exception processing format is summarized as follows:
""" Try: The code generally puts some code that we think might be wrong except error type: Here you can use the as+ variable name to receive error message error after executing code It is common to write error messages into the log file ... Multiple except can be written to determine a variety of error types else: Normal code code executing code "" ", regardless of exception or not
Special: Finally, usually in the function to do exception handling, and return encountered will also be normal execution, you can do some finishing work, such as: Close open files.
deffunc ():Try: F= Open ('Except_file','W') F.write ('Test') returnTrueexcept: returnFalsefinally: Print('This is finally') F.close ()Print(Func ())
Special: Universal Exception Type: Exception
Try : Print (i) except Exception as Error: Print (' error:%s'% error) """ Although there is a universal exception handling mechanism, but can predict the exception is to be handled separately and separate exception handling content to be before the almighty " " "
Python Advanced exception handling