Catalog
Nature of anomaly mechanism
try...except structure
try... Multiple except structure
try...except...else structure
try...except...finally structure
return Statement and exception handling problems
Solutions to common exceptions
1. SyntaxError: Grammar mistakes
2. NameError: Try to access a variable that is not declared
3. ZeroDivisionError: Divisor is 0 error ( Zero division error )
4. ValueError: Numerical error
5. TypeError: Type error
6. AttributeError: Access nonexistent properties of the object
7. IndexError: Index out of range exception
8. KeyError: The keyword of the dictionary does not exist
Summary of common exceptions
with Context management
trackback modular
Custom exception classes
Exception refers to the abnormal phenomenon in the process of program operation , For example, user input error 、 Divisor is zero. 、 Need to be File to process does not exist 、 Array subscript out of bounds, etc .
Exception handling , It means that the program can still correctly execute the remaining programs in case of problems , and Program execution will not be terminated due to exceptions .
python in , Introduced many classes to describe and handle exceptions , be called Exception class . Exception class definition It contains the information of this kind of exception and the methods to handle the exception .
python Inheritance hierarchy of built-in exception classes in :
Python Everything in is the object , Exception handling steps :
1. Throw an exception : When executing a method , If something unusual happens , Then this method generates a code representing the An object of exception , Stop the current execution path , And submit the exception object to the interpreter .
2. Capture exception : When the interpreter gets the exception , Look for the appropriate code to handle the exception .
try Blocks contain code that may throw exceptions ,except Blocks are used to catch and handle exceptions that occur . When it comes to execution , If try No exception was thrown in the block , Then skip ecept Block continues to execute subsequent code ; When it comes to execution , If try An exception occurred in the block , Then skip try Subsequent code in block , Jump to the corresponding except Handle exception in block ; After handling the exception , Continue with subsequent code .
try:
print("step1")
a = 3/0
print("step2")
except BaseException as e:
print("step3")
print(e)
print("End")
step1
step3
division by zero
End
try:
print("step1")
a = 3/2
print("step2")
except BaseException as e:
print("step3")
print(e)
print("End")
step1
step2
End
try:
a = input(" Please enter the dividend :")
b = input(" Please enter divisor :")
c = float(a)/float(b)
print(c)
except ZeroDivisionError:
print(" abnormal : The divisor cannot be zero 0")
except TypeError:
print(" abnormal : Both divisor and divisor should be numeric type ")
except NameError:
print(" abnormal : Variable does not exist ")
except BaseException as e:
print(e)
print(type(e))
try...except...else The structure adds “else block ”. If try No exception was thrown in the block , execute else block . If try An exception is thrown in a block , execute except block , Don't execute else block .
try:
a = input(" Please enter the dividend :")
b = input(" Please enter divisor :")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(" The result of division is :",c)
try...except...finally In structure ,finally The block is executed whether or not an exception occurs . Usually used to release try In block Resources requested .
try:
a = input(" Please enter a divisor :")
b = input(" Please enter a divisor :")
c = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print(" I am a finally The statement in , Whether it's abnormal or not , All implemented !")
print(" Program end !")
try:
f = open("d:/a.txt",'r')
content = f.readline()
print(content)
except BaseException as e:
print(e)
finally:
f.close() # Release resources . Exceptions may also occur here . If something unusual happens , Then the program is terminated , No further execution
print("step4")
def test01():
print("step1")
try:
x = 3/0
except:
print("step2")
print(" abnormal :0 Can't do divisor ")
finally:
print("step4")
print("step5")
return "e" # It is generally recommended to put it at the end of the method .
print(test01())
step1
step2
abnormal :0 No division
step4
step5
e
with Context management can automatically manage resources , stay with After the code block is executed, the code before entering the code is automatically restored Scene or context . Jump out of... For whatever reason with block , Whether there is any abnormality or not , Always ensure the normal release of resources .
with open("d:/a.txt") as f:
for line in f:
print(line)
import traceback
try:
print("step1")
num = 1/0
except:
traceback.print_exc()
Custom exception classes are generally run-time exceptions , Usually Inherit Exception Or its subclasses . Naming is generally based on Error、Exception For the suffix .
Custom exception is defined by raise Statement actively throws .
class AgeError(Exception): # Inherit Exception
def __init__(self,errorInfo):
Exception.__init__(self)
self.errorInfo = errorInfo
def __str__(self):
return str(self.errorInfo)+", Age error ! belong 1-150 Between "
if __name__ == "__main__": # If True, Then the module runs as a separate file , You can execute test code
age = int(input(" Enter an age :"))
if age<1 or age>150:
raise AgeError(age)
else:
print(" Normal age :",age)