Python Use special objects called exceptions to manage errors that occur during program execution . Whenever something happens Python Lost in error , It creates an exception object . If you write code to handle the exception , The program will continue to run ; If you did not handle the exception , The program will stop , And display a traceback, It contains reports of exceptions .
# Exceptions are used try-except-else Code block processing .try-except Block of code to Python Performs the specified operation , At the same time to tell Python What happens when something unusual happens . Used try-except When a code block , Even if there is an anomaly , The program will continue to run : Displays the friendly error message you wrote , Not to confuse the user traceback.
# Use exceptions to avoid crashes
【 Principle of use 】: By putting in code that might cause an error try Block of code , When in try Block of code , Caught an exception , execute except Code block at , Do exception handling , On the contrary, if an exception is caught , execute else Code block at .
try:
print(5 / 0)
except ZeroDivisionError:# Divisor is 0 It's abnormal
print("You can't divide by zero!")
#pass # Don't do anything? , Just skip
else:# If exception is caught , execute else Block code
print("hello")
1、Python Trying to perform try Code in a code block ; Only code that might throw an exception needs to be placed try In the sentence .
2、 occasionally , There are some only in try The code that needs to be run for a block to execute successfully ; This code should be placed else Block of code .
3、except Code block tells Python, If it tries to run try The specified exception is thrown when the code in the code block , What should I do .
4、pass sentence pass The statement also ACTS as a placeholder , It reminds you that you're not doing anything somewhere in the program, right , And what might he do here in the future , Don't do anything? , Just skip .
【 Common abnormal 】:
(1) FileNotFoundError abnormal : The specified file was not found
(2)ZeroDivisionError abnormal : The divisor is 0
(3)TypeError abnormal : Wrong input type
...