Chapter one Python introduction
Chapter two Python Basic concepts
The third chapter Sequence
Chapter four Control statement
The fifth chapter function
Chapter six Object oriented fundamentals
Chapter vii. Object oriented depth
Chapter viii. Exception mechanism
In this chapter , We will first understand what an exception is : The software program is running , You may encounter problems that can make it not work properly , We call it an exception , English is : Exception
then , We will learn about the four structural ways to catch exceptions ,
And then , We sort out the common anomalies
And then , We add other questions about exceptions ,
Last , We use Pycharm To experience the abnormal debugging process
An unexpected condition that occurs when a program is running , This is called an exception ,
Once an exception occurs when the program is running , Will cause the program to terminate immediately , The code after the exception will not continue to execute , So we need to deal with the exception
Nature of anomaly mechanism :
python in , Introduced many classes to describe and handle exceptions , Called exception class . The exception class definition contains the information of this kind of exception and the methods to deal with the exception .
The following is a more complete display of python Inheritance hierarchy of built-in exception classes in :
Key to exception resolution : location
When an exception occurs , The interpreter will report relevant error messages , Relevant error messages will be printed on the console .
We just need to trace it from top to bottom (Trackback) The process in which the error occurred , Finally locate the line of code that caused the error .
Practical code
# The test is simple 0 Can't do divisor exception
# Because if the hypothesis holds , shows 3/0=0 => Can be derived 0*0=3, Because the result doesn't hold , So the hypothesis doesn't hold
# a = 3/0
def a():
print("run in a() start! ")
num = 1/0
print("run in a() end! ")
def b():
print("run in b() start! ")
a()
print("run in b() end! ")
def c():
print("run in c() start! ")
b()
print("run in c() end! ")
print("step1")
c()
print("step2")
Results output
From the printout results , The bottom line approach (eg: a()) After the error , An exception will be thrown at the method position called by the upper layer .
Because the error message is output in the form of stack , So the top-level call prints first , So we'll see it first . So for the bottom layer / The most useful information is usually at the bottom .
This structure is the most common , It is also the most commonly used structure
Grammatical structure
try:
Monitored statement blocks that may throw exceptions
except BaseException [as e]:
Exception handling statement block
matters needing attention :
Practical code
def a():
print("run in a() start! ")
try:
num = 1 / 0
except BaseException as e:
print(" Execute the code here after catching the exception ")
print("run in a() end! ")
def b():
print("run in b() start! ")
a()
print("run in b() end! ")
def c():
print("run in c() start! ")
b()
print("run in c() end! ")
print("step1")
c()
print("step2")
Results output
try…except Can catch all exceptions , It's also common at work .
however , It is generally recommended to catch as many exceptions as possible ( In the order of subclass first and then parent ), And write exception handling code
To avoid missing possible exceptions , You can add... At the end BaseException . The structure is as follows
Grammatical structure
try:
Monitored 、 Statement blocks that may throw exceptions
except Exception1:
Handle Exception1 Statement block
except Exception2:
Handle Exception2 Statement block
[...]
except BaseException:
A statement block that handles exceptions that may be missing
Practical code
try:
a = input(" Please enter the dividend : ")
b = input(" Please enter divisor : ")
result = float(a)/float(b)
print(result)
except ZeroDivisionError:
print(" abnormal : 0 Can't do divisor ")
except ValueError:
print(" abnormal : The input must be of numeric type !")
except BaseException as e:
print(e)
print(type(e))
Results output
stay try…except…else On the basis of the structure 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 .
Grammatical structure
try:
Monitored statement blocks that may throw exceptions
except BaseException [as e]:
Exception handling statement block
else:
A block of statements executed when no exception is thrown
Practical code
try:
a = input(" Please enter the dividend : ")
b = input(" Please enter divisor : ")
result = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(" Divide two numbers , The result is :", result)
Results output
try…except…finally In structure , finally The block is executed whether or not an exception occurs , Usually used to release try Resources requested in block
Grammatical structure
try:
Monitored statement blocks that may throw exceptions
except BaseException [as e]:
Exception handling statement block
finally:
A block of statements that will be executed regardless of whether an exception is caught
Practical code
try:
a = input(" Please enter the dividend : ")
b = input(" Please enter divisor : ")
result = float(a)/float(b)
except BaseException as e:
print(e)
else:
print(" Divide two numbers , The result is :", result)
finally:
print(" I am a finally The statement in , Whether it's abnormal or not , All implemented !")
Output results
Practical code 2
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")
# Python Exceptions in are derived from BaseException class , We test and list some common exceptions , Easy for beginners to master
# 1. SyntaxError : Grammar mistakes | SyntaxError: invalid syntax. Perhaps you forgot a comma?
# int a =3
# 2. NameError : Try to access a variable that is not declared | NameError: name 'a' is not defined
# print(a)
# 3. ZeroDivisionError : Divisor is 0 error ( Zero division error ) | ZeroDivisionError: division by zero
# a = 3 / 0
# 4. ValueError : Numerical error | ValueError: could not convert string to float: 'skyII'
# float("skyII")
# 5. TypeError : Type error | TypeError: unsupported operand type(s) for +: 'int' and 'str'
# 123+"abc"
# 6. AttributeError : Access nonexistent properties of the object | AttributeError: 'int' object has no attribute 'sayhi'
# a = 100
# a.sayhi()
# 7. IndexError : Index out of range exception | IndexError: list index out of range
# a = [4, 5, 6]
# a[10]
# 8. KeyError : The keyword of the dictionary does not exist | KeyError: 'salary'
a = {
'name': "sari", 'age': 18}
a['salary']
because return There are two functions : End method run 、 Return value .
We don't usually put return Put it in the exception handling structure , But put it at the end of the method .
Practical code
Generally do not put return Statement placed in try、except、else、finally In block , There will be some unexpected mistakes . It is suggested to put it at the end of the method
Like the code above , This kind of writing will lead to whether it is correct or not , Will result in try Internal return To execute without execution finally The sentence inside
def testException():
try:
a = input(" Please enter the dividend : ")
b = input(" Please enter divisor : ")
result = float(a) / float(b)
return result
except BaseException as e:
print(e)
return "a"
finally:
print(" I am a finally The statement in , Whether it's abnormal or not , All implemented !")
return "b"
# return "b" # The normal situation should be put here
print(testException())
Results output
finally Blocks are executed whether or not an exception occurs , Usually we release resources as code .
Actually , We can go through with Context management , It is more convenient to release resources .
with Context management can automatically manage resources , stay with After the code block is executed, the scene or context before entering the code is automatically restored .
Jump out of... For whatever reason with block , Whether there is any abnormality or not , Always ensure the normal release of resources .
It greatly simplifies the work , In file operation 、 Network communication related occasions are very common .
Grammatical structure
with context_expr [ as var]:
Sentence block
Practical code
# 【 Example 】 with Context management file operation
with open("d:/dd.txt") as f:
for line in f:
print(line)
We can use
traceback.print_exc(file=f)
, Output the exception log to the log file
# traceback Module and generate exception logs
import traceback
try:
print("step1")
num = 1 / 0
except:
# traceback.print_exc() # Output error call records directly
with open("d:/a.log", "a") as f: # Use traceback Write exception information to the log file
traceback.print_exc(file=f)
Program development , Sometimes we need to define our own exception classes .
Custom exception classes are generally run-time exceptions , Usually inherited Exception Or its subclasses .
Naming is generally based on Error 、 Exception For the suffix . Custom exception is defined by raise Statement actively throws .
Practical code
# 【 Example 】 Custom exception classes and raise sentence
class AgeError(Exception):
def __init__(self, errorInfo):
Exception.__init__(self)
self.errorInfo = errorInfo
def __str__(self):
return str(self.errorInfo) + ", Age error ! belong 1-150 Between !"
# Test code
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)
Results output
The program runs here , Hang up for a while , Stop executing . We can observe the operation of the program in detail at this time , Facilitate further judgment
Debugging steps
To set breakpoints :
Click after the line number to add a breakpoint . Click again on the breakpoint to cancel the breakpoint
Enter the debug view
We can enter the debug view in the following three ways : Click the button on the toolbar
/ Right click the edit area , Click on : debug ‘ Module name ’
/ Shortcut key : shift+F9
After entering the debug view , The layout is as follows :
On the left “ Browse frames ”: The debugger lists the breakpoints , The method that the current thread is running , Each method corresponds to a “ Stack frame ”. At the top is the method of the current breakpoint .
Variable value observation area : The debugger lists the variable values related to the method where the breakpoint is located . We can go through it , View the change of the value of the variable .
Commissioning operation area
We use the buttons in the figure above to debug , Their meanings are as follows :