Python's Way of handling errors:
1> Assertion
assert condition equivalent to if not condition: The crash program asserts that the purpose of the setting is to cause it to crash later , instead of directly setting the error condition, let it crash directly >>> age =-1 assert 0 < Age < Assertionerror
2> Catching exceptions
Try: x=input () y=input ()Print(x/y)exceptZerodivisionerror:Print("Division by Zero") Like this try/The except form is to catch possible exception errors, and once the Zerodivisionerror error message occurs, the code after the except Zerodivisionerror is run through multiple except to catch different error messages defCalc (expr):Try: returneval (expr)exceptZerodivisionerror:Print("Divison by Zero") exceptTypeError:Print('This is not a number?') a block captures multiple error messagesdefCalc (expr):Try: returneval (expr)except(Zerodivisionerror, TypeError):Print("Input has some bugs") Print error messagedefCalc (expr):Try: returneval (expr)except(Zerodivisionerror, TypeError) as Error:Print(Error) Information processing for other errorsdefCalc (expr):Try: returneval (expr)exceptZerodivisionerror:Print("Divison by Zero") except: Print('haha, something unknown happened!'Else statement is used to avoid error messagesdefCalc (expr):Try: returneval (expr)exceptZerodivisionerror:Print("Divison by Zero") Else: Print("Oh, it goes well!"There is also a finally statement that performs the actual application, whether or not the error is true: (input expression until it can be evaluated) whileTrue:Try: Print(eval (input ()))except: Print('reinput until you input the correct expression!') Else: Break; finally: Print('I love the World whatever!')#even if the else break also executes finally
Python learns the third bullet: How is the exception handled?