First, catch the exception
1, try except
# !usr/bin/env python # -*-coding:utf-8-*-num = input (" Please enter a number:")try: = Int (num) + print(int_num)except: Print (" you are not entering a number ")
2. Capturing specific error messages
Try except Exception as E
# !usr/bin/env python # -*-coding:utf-8-*-num = input (" Please enter a number:")try: = Int (num) + print(int_num)except Exception as E: # all exceptions of the exception class can be captured, which is the base class for all exception classes Print (e)
3. Capturing multiple exceptions
#!usr/bin/env python#-*-coding:utf-8-*-num = input ("Please enter a number:")Try: Int_num= Int (num) + 100Print(Int_num)exceptValueError as E:#only the ValueError type is captured, and the except code behind the capture is no longer running Print("occur valueerror")exceptIndexerror as E:#only the Indexerror type is captured, and the except code behind the capture is no longer running Print("occur indexerror")exceptException as E:#capturing all exception types Print("occur exception")
4, the complete anomaly structure
#!usr/bin/env python#-*-coding:utf-8-*-Try: #the code statement to catch the exception PassexceptValueError as E:#executes this block of code if a ValueError exception is caught Print(e)exceptException as E:#Execute code block if error ValueError not captured Print(e)Else: #Execute the code block if the code block under try does not have an exception Print("no exception occurred")finally: #executes the code block regardless of the publication error Print("End")
5. You can throw exception information yourself
# !usr/bin/env python # -*-coding:utf-8-*- input_num = input (" Please enter a number greater than 0: ) try : Span style= "COLOR: #0000ff" >if int (input_num) <= 0: raise Exception (" number cannot be less than or equal to 0 ") # Create a Exception object except Exception as E: print (E)
In the above code, the E is the exception object, and print (e) can print out the text, the principle is to use the __str__ (self) Special method:
#!usr/bin/env python#-*-coding:utf-8-*-classFoo:def __init__(SELF,EF): Self.ef=EFdef __str__(self):returnself.efexception= Foo ('something went wrong .... ')Print(Exception)#something went wrong .... , the __str__ (self) method is actually called
6. Assertion
Typically used for testing, assert conditions, if the condition is set to execute, the condition is not set up directly throws an exception
# !usr/bin/env python # -*-coding:utf-8-*- Assert 2 = = 2assert 1 > 2 # because the condition is not set, it will throw the exception directly
Python path 32 python exception handling