Python exception handling and python exception handling
1. What is an exception?
An exception occurs when a program encounters a bug or an error occurs during running. If a program fails normally, the program will be interrupted. If you do not want the program to be terminated, so you have to handle the exceptions. This is the meaning of the exceptions.
2. Exceptions include common exceptions, actively triggered exceptions, and custom exceptions.
The syntax structure of exception handling is as follows:
Str1 = 'A' try: # main logic processing code int (str1) handle T IndexError, e: # specify the exception information print "IndexError! "Failed t Exception, e: # This is a universal Exception capture print eelse: # passfinally: # If no Exception exists, pass is executed.
In addition to automatically triggering exceptions, we can also actively trigger exceptions. The structure is as follows:
Automatic trigger exception
Try: raise Exception ('error... ') failed t Exception, e: print e
Custom Exception (define a class that inherits from the Exception class and then define the _ str _ method to process the returned value)
Class myException (Exception): def _ init _ (self, msg): self. message = msg def _ str _ (self): return self. message try: raise myException ('My exception') failed t myException, e: print e
Assertions
Assert Condition
An error is returned only when the condition is true. Commonly Used for program debugging