1) Motivation:
Why we need it?
If the 'demo_read.txt' is not exist yet, we will encounter 2 issues:
a) The script will exit immediately
b) The script will print a bit verbose and messy error message:
Traceback (most recent call last):
File "c:\Users\liuga\git_downloads\study\python\pickle_notes.py", line 1, in <module>
open('demo_read.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'demo_read.txt'
Can we continue run the script without exiting?
Can we print out a clean or better customized error messages?
Yes, yes, Let's move on.
2) Better way!
The terminal will display:
[Errno 2] No such file or directory: 'demo_read.txt'
3) What is more?
Example 1:
When running it, terminal will display:
Everthing is fine, no error!
The try-block is done no matter what happens. You will always see this line
Example 2:
When running it, terminal will display:
name 'y' is not defined
The try-block is done no matter what happens. You will always see this line
Example 3:
When running it, terminal will display:
processing demo_read0.txt
[Errno 2] No such file or directory: 'demo_read0.txt'
The try-block is done no matter what happens. You will always see this line
processing demo_read.txt
Everthing is fine, no error for demo_read.txt
The try-block is done no matter what happens. You will always see this line
Conclusion:
Now I would like to sum up the try-block with my own language as this: it is a mechanism to handle error with more choices.
This article is inspired by [1]
Reference:
[1] https://www.youtube.com/watch?v=NIWwJbo-9_8