Exception: program run times wrong
About exception Handling:
The programmer compiles a specific code to catch the exception, which is not related to the program logic, but only to exception handling. Capturing succeeds enters another processing branch, executes its custom logic, and causes the program to fail.
1. Use the IF-judgment:
Num1=input ('>>:')#Enter a string to tryifnum1.isdigit (): Int (NUM1)#Our Orthodox program is here, and the rest belongs to the exception-handling category .elifnum1.isspace ():Print('Enter a space and execute my logic here.')elifLen (num1) = =0:Print('the input is empty, just execute my logic here.')Else: Print('other situations, execute my logic here.')
Summarize:
If-judging exception handling can only be done for a certain piece of code, the same type of different code segments also need to repeat if for processing
Frequent use of if results in poor readability of the program itself
If it is possible to resolve the exception, there is only the above problem
2. Use the PY specific syntax:
1. Basic syntax
Try : instrumented code block except exception type: When an exception is detected in a try, the logic for this position is executed
2. Exceptions can only handle specified exception conditions and cannot be handled if unspecified exceptions
# exception not caught, program directly error ' Hello ' Try : int (s1)except indexerror as E: print(e)
3. Universal exception:exception can catch any exception
' Hello ' Try : int (s1)except Exception as E: print(e) for ' Hello ' # It won't go red, but it will also show related errors
If any exceptions are uniformly discarded, then a exception is sufficient.
Multi-branch processing is required if you want to customize different processing logic for different exceptions
' Hello ' Try : float (S1)except indexerror as E: print(e)except Keyerror as E: print(e)except valueerror as E: Print(e)
4. Other organizational structures
S1 ='Hello'Try: Int (s1)exceptIndexerror as E:Print(e)exceptKeyerror as E:Print(e)exceptValueError as E:Print(e)#except Exception as E:#print (e)Else: Print('execute My code block without exception in try')finally: Print('The module is executed whether it is unusual or not, usually for cleanup work'# This step will be done anyway
5. Proactively triggering exceptions
Try : Raise TypeError (' type error ')except Exception as E: Print (e)
15.python Exception Handling