An exception occurred while writing the program, and the program may not function correctly. In this case, you need to introduce exception handling
1.try ... except
Try to write the normal running program code, except is the exception condition
1 a=3 2 b=2 3 for in range (5): 4 try: 5 a = A-1 6 c=b/a 7 print(c) 8 9 except Exception as E: Ten Print (e) #输出异常行为名称
The result is shown below, with the name of the exception behavior (division by zero)
2.try ..... except...else statement, when no exception occurs, the statement in else will be executed
A=3b=2 for in range (3): try: = A-1 C=b/ a Print (c) except Exception as E: Print (e) Else : Print (" normal operation ")
When an exception occurs, the Else statement is not run
3.
when a try ... finally statement is executed , the statement in finally is executed, regardless of whether the exception occurred or not, until the end of the program.
#Author:wang YueA=3b=2 forIinchRange (3): Try: A= A-1C=b/aPrint(c)exceptException as E:Print(e)Else: Print("normal Operation") finally: Print("finally")
4.raise throws an exception, for example, when a condition does not satisfy the user's intention to throw an exception
A=3if a<4: Exception
elseprint(a)
Python exception handling--try except else raise finally