and JAVA The language is the same ,Python Also used try Keyword to handle exceptions .
Why is it important to handle exceptions ? Main cause : A lot of operations are just ‘ Try ’ Only then knew will succeed . such as , use python Open one txt file , And put txt The string in the file is converted to an integer .
try There are usually “try... except...”, There can be "try...finally" etc. . We see first "try...except...",
Experiment preparation :
1. One txt file ,t1.txt, It's about "123":
123
2. One python Script , try.py :
file_path = 't1.txt'
try:
f = open(file_path, 'r')
str_content = f.read()
a = int(str_content)
print(a)
except Exception:
print('hh')
Run script directly , Will find except Below print('hh') Will not run . because txt The contents of the document are normal ( It's a numeric string ). that , If you put t1.txt Replace the content in with :
abc
Run again try.py, You will find that the script will only output 'hh', Note that the code reported an exception . Because the characters 'abc' No way int() It becomes an integer number .
Come here , A basic exception handling experiment is completed . Keep looking down ,
If t1.txt The document doesn't exist ? python The script reads this txt when , There will also be exceptions , This is another anomaly . Do not modify the above script try.py Code running in , Will find out or will output 'hh', Report exception . But as an old driver of code , Still want to distinguish these two kinds of abnormality . that , We need more detailed code reporting , Revised as follows :
file_path = 't1.txt'
try:
f = open(file_path, 'r')
str_content = f.read()
a = int(str_content)
print(a)
except ValueError:
print(file_path + ' The content in cannot be converted to a number !')
except FileNotFound:
print(file_paht + ' file does not exist !')
except Exception:
print(' Unknown error !')
In this way, Ma liuer deals with two different kinds of anomalies . there except It's followed by "ValueError" and "FileNotFound" How do you know the key words ? Just make the same exception , see console Just a hint .
Come here ,try...except... The key words are almost the same . Let's see finally Usage of :
file_path = 't1.txt'
try:
f = open(file_path, 'r')
str_content = f.read()
a = int(str_content)
print(a)
except Exception:
print(' Unknown error !')
finally:
print(file_path)
comparison except for ,finally Keywords are much simpler , Represents the last running code . Whether there is any abnormality or not , Code blocks that will run , We'll put it in finally in . that , The above code is equivalent to :
file_path = 't1.txt'
try:
f = open(file_path, 'r')
str_content = f.read()
a = int(str_content)
print(a)
except Exception:
print(' Unknown error !')
print(file_path)
The official description is :
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.