Exception: An error is reported when the program is running
About exception handling:
Programmers have programmed specific codes to catch exceptions. This code has nothing to do with program logic, but only with exception handling. If the capture is successful, it will enter another processing branch and execute the logic customized for it, so that the program will not crash
1. Use the if judgment formula:
num1=input( ' >>: ' ) #Enter a string and try if num1.isdigit(): int(num1) #Our orthodox program is put here, and the rest belong to the category of exception handling elif num1.isspace(): print ( ' If the input is a space, execute my logic here ' ) elif len(num1) == 0: print ( ' If the input is empty, execute my logic here ' ) else : print ( ' In other cases, execute my logic here ' )
Summarize:
The if-judgmental exception handling can only be used for a certain piece of code, and it is necessary to repeat the if for the same type of different code segments.
Frequent use of if will make the program itself less readable
if is able to solve the exception, but the above problems exist
2. Use py-specific syntax:
1. Basic grammar
try: Checked code block except exception type: Once an exception is detected in try, the logic at this position is executed
2. Exceptions can only handle specified exceptions, if non-specified exceptions cannot be handled
#Uncaught exception, the program reports an error directly s1 = ' hello ' try : int(s1) except IndexError as e: print(e)
3. Universal exception: Exception can catch any exception
s1 = 'hello' try: int(s1) except Exception as e: print (e) ---invalid literal for int() with base 10: ' hello ' #It will not be red, but it will also display related errors
If all exceptions are discarded uniformly, then one Exception is enough
If you want to customize different processing logic for different exceptions, you need multi-branch processing
s1 = 'hello' try: float(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e)
4. Other organizations
s1 = 'hello' try: int(s1) except IndexError as e: print (e) except KeyError as e: print (e) except ValueError as e: print (e) # except Exception as e: # print(e) else : print ( ' If there is no exception in the code block in try Execute me ' ) finally : print ( ' Whether there is an exception or not, the module will be executed, usually to clean up ' ) # This step will be executed at the end no matter what
5. Actively trigger exceptions
try : raise TypeError( ' type error ' ) except Exception as e: print (e)