Copyright, without permission, is prohibited reprint
chapter
- Python Introduction
- Python development environment to build
- Python syntax
- Python variables
- Python Value Type
- Python type conversion
- Python String (String)
- Operators Python
- Python list (list)
- Python tuples (Tuple)
- Python collection (Set)
- Python dictionary (Dictionary)
- Python If … Else
- Python While loop
- Python For loop
- Python functions
- Python Lambda
- Python Classes and Objects
- Python inheritance
- Python iterator (Iterator)
- Python module
- Python date (Datetime)
- Python JSON
- Python regular expression (RegEx)
- Python PIP package manager
- Python exception handling (Try ... Except)
- Python Open File (File Open)
- Python read file
- Python write file
- Python delete files and folders
try
Block so that you can detect errors in the code block.
except
Block so that you can handle the error.
finally
Block so that you can execute the final code, regardless of try
the except
outcome of the block, finally
code block will be executed.
Exception Handling
When an error (or abnormal) occurs, Python will usually stop the execution and error.
These exceptions can use try
/ except
statement processing:
Examples
The following try
block exception is generated, because x
there is no definition:
try:
print(x)
except:
print("发生异常")
Because the try
block error is raised, so the except
block will be executed.
If you do not try
block, the program will crash and raise an error:
Examples
This statement generates an error because x
there is no definition:
print(x)
Except more
May define a plurality of except
, for example, may be defined as a special error code blocks except a special:
Examples
This statement generates an error because x
there is no definition:
try:
print(x)
except NameError:
print("变量x没有定义")
except:
print("其他错误")
else
Can use else
keyword to define a code block, if no error occurs, else
the code block is executed:
Examples
In this example, try block does not produce any error:
try:
print("你好")
except:
print("出错了")
else:
print("一切正常")
finally
If you define a finally
block, regardless of try
whether the block error is raised, it will execute finally
the block.
Examples
try:
print(x)
except:
print("出错了")
finally:
print("'try except'处理结束")
This is useful for close objects, cleaning up resources:
Examples
Try not to write a document written:
try:
f = open("test.txt")
f.write("奇客谷教程")
except:
print("写文件出错了")
finally:
f.close() # 关闭文件
The file is closed.